简体   繁体   中英

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 ?

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:

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.


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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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