2015-10-26 107 views
-1

我使用的是string.split(':')功能,使我的清单包括姓名的:名字对(例如["John", "Doe", "Alex", "Jacobson" ...]干净的方式来遍历在Python中成对的列表?

我知道如何使用一个基本的for循环,我将有两名每次递增指数(并比较长),但我想以更具体Python的方式处理它

是否有任何更清晰的循环构造,我可以采取哪些让我考虑前两个指标,然后接下来的两个, etc?

+0

https://docs.python.org/2/library/functions.html#zip – asf107

+0

的可能的复制【什么是最“Python化”的方式来遍历一个列表chunks?](http://stackoverflow.com/questions/434287/what-is-the-most-pythonic-way-to-iterate-over-a-list-in-chunks)和[另一种方法来拆分列表成组的n](http://stackoverflow.com/questions/1624883/alternative-way-to-split-a-list-into-groups-of-n/1625023)和[你如何将列表分成均匀Python中的大小块](http://stackoverflow.com/questions/312443/how-do-you-split-a-list-into-evenly-sized-chunks-in-python) – TessellatingHeckler

回答

1
for first,last in zip(string[::2],string[1::2]): 

应该工作

编辑:对不起,我并不是很简洁。

zip所做的是创建一个允许for循环中有两个变量的对象。在这种情况下,我们创建一个zip对象,其中包含从索引0(string[::2])开始的所有其他对象的切片列表以及从索引1(string[1::2')开始的每个其他对象的切片列表。然后我们可以使用两个迭代器(first,last)遍历该zip列表。

即。

>>> 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 
+0

究竟发生了什么? – AlwaysQuestioning

+0

为什么要这样工作?如果你必须说(并且只是说)“这应该起作用”,这可能是一个不好的答案。自我解释 –

+0

我道歉,检查编辑 –

1
>>> import itertools 
>>> L = ["John", "Doe", "Alex", "Jacobson"] 
>>> for fname, lname in zip(*itertools.repeat(iter(L), 2)): print(fname, lname) 
... 
John Doe 
Alex Jacobson 
0

您可以使用拼接,即 假设所有的名字都在X

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

现在你可以很容易地通过迭代,

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

呼叫iter上列表和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)每次都从我们的迭代器中消耗两个元素,直到迭代器耗尽,所以我们最终得到配对的姓和名。这是有点相当于:

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') 
+0

哪些可以推广到''n'作为['zip(* [iter(xs)] * n)'](http://stackoverflow.com/a/16758257/ 478656) – TessellatingHeckler