简体   繁体   English

循环 python 在一行中的多个分配

[英]multiple assignments in one line for loop python

I would like a one line way of assigning two variables to two different values in a for loop.我想要一种在 for 循环中将两个变量分配给两个不同值的单行方式。

I have a list of list of values我有一个值列表

list_values = [[1, 2, 3], [4, 5, 6]]

I have tried to do this, and it works but is not pythony:我试过这样做,它可以工作但不是pythony:

first = [i[0] for i in list_values]
second = [i[1] for i in list_values]

Which makes:这使得:

first = [1, 4]
second = [2, 5]

I want to write something like:想写一些类似的东西:

first, second = [i[0]; i[1] for i in list_values]

Is something like this possible?这样的事情可能吗?

You could use the zip() function instead: 您可以改用zip()函数

first, second = zip(*list_values)[:2]

or the Python 3 equivalent: 或等效的Python 3:

from itertools import islice

first, second = islice(zip(*list_values), 2)

zip() pairs up elements from the input lists into a sequence of new tuples; zip()将输入列表中的元素配对为一系列新的元组; you only need the first two, so you slice the result. 您只需要前两个,就可以对结果进行切片。

list_values = [[1, 2, 3], [4, 5, 6]]

first, second = [[i[0], i[1]] for i in list_values]

Next time use something other than the "i", like "elem" etc.下次使用“i”以外的东西,比如“elem”等。

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

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