繁体   English   中英

如何从 python 编程中的列表列表中提取一个特定物种的值?

[英]How to extract values of one specific specie from a list of list of list in python programming?

我在 Python 数据中有一个列表列表。 所有值都对应于数据中的每个物种。 我想提取特定物种的价值。 每个对应的值都在每个列表中。 假设我有三种铜、银、金和铂。 在三个不同的温度下,它们的频率如下:

Frequency = [[{1}, {2}, {3}, {4}], [{1},{22}, {44}, {54}], [{23}, {43}, {52}]

请记住,每个列表的第三个值是“Au”,即 3、44、43。 所以,我需要像[3,44,43]这样的答案。

我冒昧地使用了defaultdict ,所以我们可以按元素名称索引我们的结果。

由于我们是从集合中提取结果(例如{1} ),我们可以使用iter返回值的迭代器,然后调用next来提取第一个值。

from collections import defaultdict
frequencies = [[{1}, {2}, {3}, {4}], [{1}, {22}, {44}, {54}], [{23}, {99}, {43}, {52}]]
res = defaultdict(list)
for i, element in enumerate(['Cu','Ag','Au','Pt']):
  for j in range(len(frequencies)):
    res[element].append(next(iter(frequencies[j][i])))
for element in res:
  print(f'{element} temperatures was {res[element]}')

Output:

Cu temperatures was [1, 1, 23]
Ag temperatures was [2, 22, 99]
Au temperatures was [3, 44, 43]
Pt temperatures was [4, 54, 52]

首先,你写的不是一个列表的列表。 正如wjandrea所说:

这是集合列表的列表,而不是列表

其次,由于我无法清楚地理解您的问题,我想您需要一种从每个列表中提取特定值的方法。 为此,您可以使用NumpyPandas (假设您熟悉它们,否则请阅读以获取更多信息)

我这样做的方式可能是:

# in order to make a list of *temperatures* for *each* element we should first
# take the given array -- yours in this case -- and convert it into an array:
 
freq = np.array([[1, 2, 3, 4], [1,22, 44, 54], [np.nan, 23, 43, 52]]).T

# then we would create a DataFrame out of our array using our elements' names as 
# the indexing name:

data_frame = pd.DataFrame(freq, index=["Cu", "Ag", "Au", "Pt"], columns=["temp_1", "temp_2", "temp_3"])

结果:

    temp_1  temp_2  temp_3
Cu      1      1      0
Ag      2     22     23
Au      3     44     43
Pt      4     54     52

ps 您还可以通过以下方式获得例如“Ag”元素的温度:

data_frame.loc["Ag"]

或者,如果您想要一列的整个温度,只需编写:

data_frame["temp_1"]

暂无
暂无

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

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