简体   繁体   English

如何在python中使用三种类型的列表制作嵌套列表?

[英]how to make a nested list with three types of lists in python?

I have three lists:我有三个清单:

EX_Num = [1.0, 2.0, 3.0]
Height_str = ['tall', 'medium', 'short']
total_carbon = [8.425169446611104, 8.917085904771866, 6.174348482965436]

How do I make a nested list where column1 = EX_Num , column2 = Height_str and column3 = total_carbon ?如何制作一个嵌套列表,其中column1 = EX_Numcolumn2 = Height_strcolumn3 = total_carbon

It's not clear what you are asking... but if you just want a list of lists, just append them.不清楚你在问什么......但如果你只想要一个列表列表,只需附加它们。

>>> nested_list.append(EX_Num)
>>> nested_list.append(Height_str)
>>> nested_list.append(total_carbon)
>>> nested_list
[[1.0, 2.0, 3.0], ['tall', 'medium', 'short'], [8.425169446611104, 8.917085904771866, 6.174348482965436]]

If you want all the values put into one list, just concatenate them.如果您希望将所有值放入一个列表中,只需将它们连接起来即可。

>>> nested_list = EX_Num + Height_str + total_carbon
>>> nested_list
[1.0, 2.0, 3.0, 'tall', 'medium', 'short', 8.425169446611104, 8.917085904771866, 6.174348482965436]

If you need something different, you need to make your question more clear.]如果你需要不同的东西,你需要让你的问题更清楚。]

EDIT based on comment:根据评论编辑:

If you know that all the lists are the same length:如果您知道所有列表的长度相同:

nested_list = []
# be careful, if the lists aren't all the same length, you will get errors
for x in range(len(EX_Num)):
    tmp = [EX_Num[x], Height_str[x], total_carbon[x]]
    nested_list.append(tmp)

You can use the built-in zip function to join multiple iterables together into tuples:您可以使用内置的zip函数将多个可迭代对象连接到元组中:

ex = [1.0, 2.0, 3.0]
height = ['tall', 'medium', 'short']
total_carbon = [8.4, 8.9, 6.1]

joint = zip(ex, height, total_carbon)
print(joint)

# [(1.0, 'tall', 8.4), (2.0, 'medium', 8.9), (3.0, 'short', 6.1)]

Note: please don't use "hungarian notation" for your variable names ( _num , _str , etc.) -- they're just clutter, specially in a dynamic language like Python.注:请不要使用“匈牙利命名法”为您的变量名( _num_str等) -他们只是混乱,特别是在像Python这样的动态语言。


If you need to keep related data grouped together, it's more readable to create a simple container type for it.如果您需要将相关数据组合在一起,为它创建一个简单的容器类型更具可读性。 namedtuple is great for this: namedtuple非常适合这个:

from collections import namedtuple
Thing = namedtuple('Thing', ['ex', 'height', 'total_carbon'])
my_things = [Thing(*t) for t in zip(ex, height, total_carbon)]

Now you can refer to stuff by name -- for example, my_things[0].height -- instead of needing to remember the index positions of each attribute.现在您可以按名称引用东西——例如, my_things[0].height而无需记住每个属性的索引位置。

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

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