简体   繁体   中英

Clean way to iterate through a list in pairs in Python?

I am using a string.split(':') function so that my list consists of firstname:lastname pairs (eg ["John", "Doe", "Alex", "Jacobson" ...]

I know how to use a basic for loop where I would increment the index by two each time (and compare to the length of the list), but I want to take care of it in a more Python specific way.

Are there any cleaner looping constructs I can take which would allow me to consider the first two indices, and then the next two, etc?

Call iter on the list and zip :

l = ["John", "Doe", "Alex", "Jacobson"]

it = iter(l)

for f,l  in zip(it, it):
    print(f,l)

John Doe
Alex Jacobson

zip(it,it) just consumes two elements from our iterator each time until the iterator is exhausted so we end up getting the first and last names paired. It is somewhat equivalent to:

In [86]: l = ["John", "Doe", "Alex", "Jacobson"]

In [87]: it = iter(l)

In [88]: f,l = next(it),next(it)

In [89]: f,l
Out[89]: ('John', 'Doe')

In [91]: f,l
Out[91]: ('Alex', 'Jacobson')
for first,last in zip(string[::2],string[1::2]):

should work.

EDIT: sorry, I wasn't really being concise.

What zip does is create an object that allows two variables in a for loop. In this case, we are creating a zip object with a sliced list of every other object starting at index 0 ( string[::2] ) and a sliced list of every other object starting at index 1 ( string[1::2' ). We can then use two iterators ( first,last ) to iterate through that zip list.

ie.

>>> l1 = [1,2,3,4]
>>> l2= [5,6,7,8]
>>> zip(l1,l2)
<zip object at 0x02241030>
>>> for l,k in zip(l1,l2): print(l+k)
...
6
8
10
12
>>> for l,k in zip(l1,l2): print (l,k)
...
1 5
2 6
3 7
4 8
>>> import itertools
>>> L = ["John", "Doe", "Alex", "Jacobson"]
>>> for fname, lname in zip(*itertools.repeat(iter(L), 2)): print(fname, lname)
...
John Doe
Alex Jacobson

You can use splicing, ie, Assuming all the names are in x

fname = x[::2]
lname = x[1::2]
y = []
for a,b in zip(fname,lname):
    y.append({'fname':a,
              'lname':b,})

Now you can easily iterate by,

for i in y:
    print i['fname'], i['lname']

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM