Remove bracket in a list of tuples in tuples - python

I would like to remove the bracket of a tuples who belong to tuples within a list:
Here's an example:
List_1 = [(0, (1, 1)),
(0, (1, 2)),
(0, (1, 3))]
And the expected output should look like this:
list_2 = [(0, 1, 1),
(0, 1, 2),
(0, 1, 3)]
I tried this:
for element in List_n_d1d2:
newlist = (element[0], element[1])
But ended up with the same output... Could you please help me, thank you !

Use the * spread operator to expand the tuple into separate elements.
list_2 = [(a, *b) for a, b in list_1]

A simple comprehension would be:
[(a,) + b for a,b in List_1]

Related

Generating 2D grid indices using list comprehension

I would like to store the row and column indices of a 3 x 3 list in list. It should look like the following:
rc = [(0,0),(0,1),(0,2),(1,0),(1,1),(1,2),(2,0),(2,1),(2,2)]
How can I get this list using a list comprehension in Python?
Some consider multiple for loops inside a list comprehension to be poor style. Use itertools.product() instead:
from itertools import product
list(product(range(3), repeat=2))
This outputs:
[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2)]
How about:
[(x, y) for x in range(3) for y in range(3)]
If I understand correctly, and the input is A, the B can be output as follows:
A = [[1,2,3],[4,5,6],[7,8,9]]
B =[(A[i], A[j]) for i in range(3) for j in range(3)]

List to list of tuples conversion

I am brand new to Python. I can change a list to a tuple, for example
li = [1]
tuple(li)
I am trying to create a tuple that gives the item and its position, so a tuple that would come out (1, 0). I have no idea how to get started.
If you want a tuple of tuples, you can use a generator expression like this;
li = [4, 5, 6]
tuple((li[i], i) for i in range(len(li)))
Or with enumerate;
tuple((v, k) for k,v in enumerate(li))
Both will return;
((4, 0), (5, 1), (6, 2))
If you want a list of tuples, you can use a list comprehension expression like this;
[(li[i], i) for i in range(len(li))]
or with enumerate;
[(v,k) for k, v in enumerate(li)]
Both will return;
[(4, 0), (5, 1), (6, 2)]
Use enumerate which does exactly what you need, just with elements and indexes flipped:
> li = [2, 4, 6]
> [(x, i) for i, x in enumerate(li)]
[(2, 0), (4, 1), (6, 2)]
If you want a just one tuple you could do this:
li = (list[1], 1)
The brackets here are the literal syntax for tuples.
If you wanted to do it for all the elements of the list, you could use a list comprehension:
lis = [(list[i], i) for i in range(len(list))]
Which would create a list of tuples were each tuple has the element and its index.
One possible way is to use enumerate,
li = [10, 20, 30]
list(enumerate(li))
prints
[(0, 10), (1, 20), (2, 30)]
If you want the output to be in (item, position) order, you can use,
[(v, k) for k,v in enumerate(li)]
zip with range is another option:
In [4]: li = [2,4,6]
In [5]: zip(li, range(len(li)))
Out[5]: [(2, 0), (4, 1), (6, 2)]

Subtract two lists of tuples from each other

I have the these two lists and I need to subtract one from the other but the regular "-" won't work, neither will .intersection or XOR (^).
A = [(0, 1)]
B = [(0, 0), (0,1), (0, 2)]
Essentially what I want is:
B - A = [(0, 0), (0, 2)]
You can use list comprehension to solve this problem:
[item for item in B if item not in A]
More discussion can be found here
If there are no duplicate tuples in B and A, might be better to keep them as sets, and use the difference of sets:
A = [(0, 1)]
B = [(0, 0), (0,1), (0, 2)]
diff = set(B) - set(A) # or set(B).difference(A)
print(diff)
# {(0, 0), (0, 2)}
You could perform other operations like find the intersection between both sets:
>>> set(B) & set(A)
{(0, 1)}
Or even take their symmetric_difference:
>>> set(B) ^ set(A)
{(0, 0), (0, 2)}
You can do such operations by converting the lists to sets. Set difference:
r = set(B)-set(A)
Convert to list if necessary: list(r)
Working on sets is efficient compared to running "in" operations on lists: using lists vs sets for list differences

Python: Remove a Sublist Which Contains Only One Instance of an Item

everyone! Basically, I need to remove every sublist from a list which contains only one of any item - so long as that item itself is not one.
Here's an example: If I had this,
list = [(0, 0), (0, 1), (0, 2), (1, 1), (1, 0), (1, 3), (2, 0), (0, 3)]
I would in turn want this:
list = [(0, 0), (1, 1)]
What I originally tried was:
for sublist in list:
for item in sublist:
if sublist.count(item) == 1 and item != 1:
list.remove(sublist)
Unfortunately, this interfered with the cycling of the original for-loop (I think), so I would end up with things like: ValueError: list.remove(x): x not in list Any help appreciated.
EDIT: I'd like to apologize, (1, 3) should not be in the output! Sorry for the confusion, hopefully this program will be better at doing this than I am!
Copy the list before running the for loop, so the iterable don't get modified during the loop
Remove one sublist once and break, don't try to remove it twice.
Though I'm only getting [(0, 0), (1, 1)] but not (1,3) in output.
for sublist in list[:]:
for item in sublist:
if sublist.count(item) == 1 and item != 1:
list.remove(sublist)
break
I'm not sure I understand the task but changing list while iterating it is never a good idea.
try to copy it first and then iterate over the copy.
something like:
list_copy = list[:]
for sublist in list_copy:
for item in sublist:
if sublist.count(item) == 1 and item != 1:
list.remove(sublist)
note that list_copy = list will copy the reference which means changing one list will change the other as well so you want to write list_copy = list[:]
P.S.
using the list type name as a variable is a very bad idea. try to use a different name.
I must say your explanation of what the code does isn't clear.
You might want to move to while loops:
List = [(0, 0), (0, 1), (0, 2), (1, 1), (1, 0), (1, 3), (2, 0), (0, 3)]
i = 0;
o = 0;
while i<len(List):
while o<len(List[i]):
if List[i].count(o) == 1 and List[i][o] != 1:
List.remove(List[i])
o+=1
i+=1
o=0;
print(List)
I got:
[(0, 0), (0, 2), (1, 1), (1, 3), (0, 3)]
You can use the filter function to filter a list. First, write a function that takes an element of your list and returns True if the element should be in the list, and False if not. Like this:
def predicate(x):
for item in x:
if x.count(item) == 1 and item != 1:
return False
return True
Now, you can take your list (Don't call it list, since list is a function we will have to use in a second, and by calling something list you can't use said function)
l = [(0, 0), (0, 1), (0, 2), (1, 1), (1, 0), (1, 3), (2, 0), (0, 3)]
And filter it with the predicate:
itr_res = filter(predicate,l)
Note, however that this returns an iterable, and not a list. You probably want a list, so use the list function to construct one from the iterable.
res = list(itr_res)
this gives the resulting list:
[(0,0),(1,1)]
As others have noted, it is hard to figure out exactly what you want your function to filter. Your code does one thing, your example and other and your description is vague. You can try to play around with the predicate function until you get it to do what you actually want
I think that this code is right for you:
list = [(0, 0), (0, 1), (0, 2), (1, 1), (1, 0), (1, 3), (2, 0), (0, 3)]
out_list = [t for t in list if (t[0] == t[1]) or t.count(1) > 0]
This code generates a new list and then you can reassign it to your input list.
But the code above generates on your input:
[(0, 0), (0, 1), (1, 1), (1, 0), (1, 3)]
Sorry, if I understand your task incorrectly.

manipulating the output of itertools.permutations in python

I want to take a list, for instance List = [1,2,2], and generate its permutations. I can do this with:
NewList = [list(itertools.permutations(List))]
and the output is:
[[(1, 2, 2), (1, 2, 2), (2, 1, 2), (2, 2, 1), (2, 1, 2), (2, 2, 1)]]
The Problem: itertools.permutations returns a list of length 1 whose only entry is the list of all permutations of List. That is:
NewList[0] == [(1,2,2),(1,2,2),(2,1,2),(2,2,1),(2,1,2),(2,2,1)]
and
NewList[1] does not exist.
I want the output to be a list where each entry is one of the permutations. That is
NewList[0] == (1,2,2)
NewList[1] == (1,2,2)
NewList[2] == (2,1,2)
...
NewList[5] == (2,2,1)
The Question: Is there a command that will produce the permutations of List in this way? Failing that, is there a way to access the 'individual elements' of [list(itertools.permutations(List))] so I can do things with them?
>>> from itertools import permutations
>>> list(permutations([1,2,2]))
[(1, 2, 2), (1, 2, 2), (2, 1, 2), (2, 2, 1), (2, 1, 2), (2, 2, 1)]
You don't need to put it in a list again. i.e Don't do [list(permutations(...))] (By doing [] you are making a nested list and hence are unable to access the elements using testList[index], though you could do testList[0][index] but it would be better to just keep it as a list of tuples.)
>>> newList = list(permutations([1, 2, 2]))
>>> newList[0]
(1, 2, 2)
>>> newList[3]
(2, 2, 1)
Now you can access the elements by using their indices.
Why can't you do this:
NewList = [list(itertools.permutations(List))][0]
or even just this:
NewList = list(itertools.permutations(List))
By doing [ list(itertools.permutations(List)) ], you put the list of permutations (the one that you want) inside of another list. So the fix would be to remove the outer []'s

Categories

Resources