简体   繁体   English

用两种表示法遍历元组列表

[英]iterate over list of tuples in two notations

I'm iterating over a list of tuples, and was just wondering if there is a smaller notation to do the following: 我正在遍历一个元组列表,只是想知道是否有一个较小的表示法可以执行以下操作:

for tuple in list:
    (a,b,c,d,e) = tuple

or the equivalent 或同等学历

for (a,b,c,d,e) in list:
    tuple = (a,b,c,d,e)

Both of these snippits allow me to access the tuple per item as well as as a whole. 这两个片段都使我能够访问每个项目以及整个项目的元组。 But is there a notation that somehow combines the two lines into the for-statement? 但是,是否存在某种方式将这两行合并为for语句? It seems like such a Pythonesque feature that I figured it might exist in some shape or form. 似乎像Python风格的功能,我认为它可能以某种形状或形式存在。

This might be a hack that you could use. 这可能是您可以使用的hack。 There might be a better way, but that's why it's a hack. 也许有更好的方法,但这就是为什么它是hack。 Your examples are all fine and that's how I would certainly do it. 您的示例都很好,我肯定会这样做。

>>> list1 = [(1, 2, 3, 4, 5)]
>>> for (a, b, c, d, e), tup in zip(list1, list1):
       print a, b, c, d, e
       print tup

1 2 3 4 5
(1, 2, 3, 4, 5)

Also, please don't use tuple as a variable name. 另外,请不要使用tuple作为变量名。

The pythonic way is the first option you menioned: pythonic方法是您提到的第一个选项:

for tup in list:
    a,b,c,d,e = tup

There isn't anything really built into Python that lets you do this, because the vast majority of the time, you only need to access the tuple one way or the other: either as a tuple or as separate elements. Python并没有真正让您做到这一点的东西,因为在大多数情况下,您只需要以一种方式或另一种方式(作为元组或作为单独的元素)访问元组。 In any case, something like 无论如何,类似

for t in the_list:
    a,b,c,d,e = t

seems pretty clean, and I can't imagine there'd be any good reason to want it more condensed than that. 看起来很干净,我无法想象有什么充分的理由希望它比以前更简洁。 That's what I do on the rare occasions that I need this sort of access. 这是我在极少数需要这种访问权限的情况下所做的事情。

If you just need to get at one or two elements of the tuple, say perhaps c and e only, and you don't need to use them repeatedly, you can access them as t[2] and t[4] . 如果只需要获取元组的一个或两个元素,只说ce ,而不必重复使用它们,则可以将它们作为t[2]t[4] That reduces the number of variables in your code, which might make it a bit more readable. 这样可以减少代码中变量的数量,这可能会使代码更具可读性。

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

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