简体   繁体   English

在Python中成对访问列表的干净方法?

[英]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" ...] 我正在使用string.split(':')函数,以便我的列表由firstname:lastname对组成(例如["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. 我知道如何使用基本的for循环,在该循环中,我每次都会将索引增加2(并与列表的长度进行比较),但是我想以一种更特定于Python的方式来处理它。

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 : 在列表上调用iterzip

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. zip(it,it)每次仅消耗迭代器中的两个元素,直到迭代器耗尽为止,因此我们最终将名字和姓氏配对。 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. zip的作用是创建一个对象,该对象在for循环中允许两个变量。 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' ). 在这种情况下,我们将创建一个zip对象,其中包含从索引0( string[::2] )开始的所有其他对象的切片列表,以及从索引1( string[1::2' )。 We can then use two iterators ( first,last ) to iterate through that zip list. 然后,我们可以使用两个迭代器( first,last )来迭代该zip列表。

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 您可以使用拼接,即假设所有名称都在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']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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