简体   繁体   English

在列表中循环元组

[英]Loop tuples inside a list

I want to make Morse code with Python, so I tried the following: 我想用Python制作摩尔斯电码,所以尝试了以下方法:

L = [(2, 1), (8, 4, 2, 1)]    
data = "00:1:02"
data = [(x[:1], x[1:]) for x in data.split(':') ]
for [a,b] in data:
    if b=="": b, a = a, '0'
    #print(a,b)

Now, I am looking for a simple way to loop trough the two tuples in the L list and separate them to make the a pass trough L[0] tuple and b pass though L[1] tuple. 现在,我在寻找一个简单的方法来循环槽两元组L列表,并把它们分开,使a通槽L[0]元组和b通虽然L[1]元组。

Something like that in one for loop: 在for循环中这样的事情:

for A in l[0], B in l[1]:

#A to do somethings with a and 
#B to do something with b

I tried some combines but I didn't find the right syntax. 我尝试了一些组合,但是找不到正确的语法。 Can any one offer any suggestions? 有人可以提供任何建议吗?

If you want to iterate over L[0] and L[1] at the same time you can use: 如果要同时遍历L[0]L[1] ,可以使用:

for a, b in itertools.izip_longest(L[0], L[1]):
    print a, b

The above will set a to None as L[1] is longer than L[0] and thus there are more values in L[1] to iterate over than in L[0] . 上面将a设置为None因为L[1]L[0] ,因此L[1]要迭代的值比L[0] This gives: 这给出:

2 8
1 4
None 2
None 1

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

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