This question already has answers here:
How do I iterate over the tuples of the items of two or more lists in Python? [duplicate]
(9 answers)
Closed 7 years ago.
I am wondering if it's posiible to iterate over two lists at once.
Something like that:
for x, m in list1, list2:
...
I know that I should use the '.items()', but I don't want to create dictionary from two lists.
Any ideas?
Use zip.
for x, m in zip(list1, list2):
zip(*iterables)
Make an iterator that aggregates elements from each of the iterables.
Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the argument sequences or iterables. The iterator stops when the shortest input iterable is exhausted. With a single iterable argument, it returns an iterator of 1-tuples. With no arguments, it returns an empty iterator.
Related
This question already has answers here:
How do I make a flat list out of a list of lists?
(34 answers)
Closed 10 months ago.
I have a code which takes input of the users and creates a nested list.
List = [list 1, list2, list 3,.....]
The list 1, list 2, list 3 and so on are dynamic and can keep increasing or decreasing.
So far my code output is:
All_data = [[a,b],[c,d],[1,2],[3,4],.....]
The output that I want (for the dynamic nested list):
All_data = [a,b,c,d,1,2,3,4,......]
Can anyone suggest me a solution to solve this?
You can use itertools.chain:
itertools.chain(*All_data)
Or:
itertools.chain.from_iterable(All_data)
This creates an iterator, if you want to get a list:
list(itertools.chain.from_iterable(All_data))
You can use numpy.concatenate(). It will condense the nested list into a single list.
If your nested list is dynamic and can grow exponentially, then I will suggest to use itertools.chain.from_iterable() from itertools library. It will be faster because it will not convert the list into a numpy array like the first option.
This question already has answers here:
Python -Intersection of multiple lists?
(6 answers)
Closed 5 years ago.
say that I have a nested list like this for example:
List = [['a','d','b'],['a','x','w','t','d'],['g','c','d','z']]
and what I want to do is find the object in the List that all the smaller lists share, so for the example List I gave 'd' would be the object they all share.
here is what I have done so far:
def related(List):
for item in List[0]:
for i in range(1, len(List)):
if item in List[i]:
return item
the problem I am having is that when I do:
related([['a','d','b'],['a','x','w','t','d'],['g','c','d','z']])
'a' is returned, but that isn't the correct answer since 'a' isn't in all the lists and only in the first 2 lists. The correct answer with that list should be 'd'.
My function basically just stops running once it finds the same object in just 1 of the lists.
Will someone be able to send me towards the right path on what I can do to get my code working correctly? Thank You!!!
What you're looking for here is the intersection of these lists. Python lists don't have an intersection functionality built-in, but sets do. We can do
def in_common(l):
if not l:
return set()
return set(l[0]).intersection(*l[1:])
This converts the first element to a set, and then finds the intersection of that set with the rest of the elements in the list.
in_common([['a','d','b'],['a','x','w','t','d'],['g','c','d','z']])
returns
{'d'}
the set containing 'd'
This question already has answers here:
python - get list of tuples first index?
(5 answers)
Closed 6 years ago.
I have a list of tuples in this format:
my_list = [(1,4),(3,6),(10,7)]
I want to print the second elements of each tupple:
4,6,7
I can access those values as:
my_list[0][1]
my_list[1][1]
my_list[2][1]
But that isn't a reasonable approach for any reasonable size list, for now, and doing using list comprehension:
[x[1] for x in my_list ]
Is there any solution that doesn't imply to use a loop?
something like:
my_list[:][1]
I tried to do it that way but got:
(3, 6)
[:] just creates a copy of the list, so [1] indexes that copy. And no, outside of NumPy arrays, there is technically no way to avoid a loop. The loop may be done in C code in a function like map(), but there's going to be a loop anyway.
Using map() for example applies a callable for each element in your input list:
map(lambda nested: nested[1], my_list)
or
from operator import itemgetter
map(itemgetter(1), my_list)
Both work in Python 2, in Python 3 you need to wrap the map() call in a list() call to drive the iteration.
Either way, I find a list comprehension to be clearer here anyway.
As mentioned in python get list of tuples first index
try with zip
my_list = [(1,4),(3,6),(10,7)]
print zip(*my_list)[1]
(4, 6, 7)
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to iterate over two lists - python
I want to iterate over two items at the same time, an iteration that in my mind looks like this:
for elem1 in list 1 and for elem2 in list2:
do something to elem1; do something to elem2
This syntax, however, is not acceptable. To be clear, I'm not talking about nested for loops, because then I'd be iterating over an entire list for every element in the first list. I want to iterate over the two lists (or whatever) in tandem. Is there a pythonic way to do this?
Use zip():
for elem1, elem2 in zip(list1, list2):
If one of these lists is longer than the other, you won't see the elements beyond the length of the shorter list.
On python 2, zip() results in a copy of both lists zipped together, and for large lists that can be a memory burden. Use itertools.izip() for such larger lists, it returns an iterator instead. On python 3, zip() itself already returns an iterator.
If you need to loop over the longest list instead (and fill in a filler value for the missing shorter list elements), use itertools.izip_longest() instead:
from itertools import izip_longest
for elem1, elem2 in izip_longest(list1, list2):
This question already has answers here:
Flatten an irregular (arbitrarily nested) list of lists
(51 answers)
Closed 6 months ago.
I asked a while ago about how to make a list of sublists (and of even more sublists) from a string given delimiters here.
How to process a string into layer of sublists
Now, I need to join them back together and I'm not sure how. I have tried to look here
Python : Recursively flatten a list
and
Flatten a list in python
However, neither of these answers work in my case because chain splits my string (single item "lists") into characters, and then therefore cannot join with "\n", and reduce does not concatenate str and list objects.
I will probably need to walk through the sublists (and their sublists) at some point. Is there a way to iterate through each level of sublist? (I can leave this as a separate question, one step at a time.. but just wondering whether this process is making sense or should I try an entire new method. I do think logically this makes the most sense, I'm just having trouble navigating it.)
Thanks.
I'm going to assume what I said in the comment is correct unless you say otherwise.
From the posts you linked, you have:
import collections
def flatten(l):
for el in l:
if isinstance(el, collections.Iterable) and not isinstance(el, basestring):
for sub in flatten(el):
yield sub
else:
yield el
to recursively flatten an irregular list of lists, and
def go(it):
for x in it:
if x == 'b':
yield [x] + list(go(it))
else:
yield x
if x == 'c':
break
to create that irregular list of lists from an iterator.
The inverse of go is just flatten(output_of_go) so the inverse of go(iter(string)) is ''.join(flatten(output_of_go)). You can see that with this test code:
lst = "aaabaabacabaacaca"
assert ''.join(flatten(go(iter(lst)))) == lst