python - 将值附加到 python 中元组的列表

标签 python python-2.7

我写过这样的代码,

x=[]
y=[]
z=[]
d={u'a':(1,2,4), u'b':(1, 0, 1), u'c':(8, 3,1)}

for k,v in d.items():
       x.append(v[0])
       y.append(v[1])
       z.append(v[2])

m=column_val(x,y) #Function call
n=column_val(x,z)

我怎样才能使这些步骤更简单而不是创建 3 个列表?

最佳答案

您可以在 d.values() 上使用 zip():

x, y, z = zip(*d.values())

这仍然会创建 3 个列表,但更加紧凑。您希望避免为各个 column_val() 参数创建循环,您最终会得到 4 个循环。

d 示例演示:

>>> d = {u'a': (1,2,4), u'b': (1, 0, 1), u'c': (8, 3,1)}
>>> x, y, z = zip(*d.values())
>>> x, y, z
((1, 8, 1), (2, 3, 0), (4, 1, 1))

请注意,xyz 中的值的顺序 不是给定的,因为字典不保留顺序。

关于python - 将值附加到 python 中元组的列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16012915/

相关文章:

python - 根据同一组中下一行中的值删除行 | Pandas

python - 通过 wheezy.template 提供静态文件 css 和 js?

python - 如果为真 : destruct Class

python - Django 从数据库生成模型

python - 将列表写入具有某些自定义格式的文件

python - r+ 和 w+ 模式之间的确切区别是什么?

python - 在 Python 中启用整数溢出

python - 尝试将 dict 写入文件时出现 KeyError [Python]

python - 我想使用 python 从文件中枚举文本

time - 在准确的时间调用函数