gpt4 book ai didi

Python列出数组中每个元素的命名索引?

转载 作者:行者123 更新时间:2023-11-30 21:53:44 25 4
gpt4 key购买 nike

我是Python新手,所以如果我的术语不正确,我深表歉意。

我有一个数组(或列表),其中充满了带有命名索引的子数组。例如:

[{'tag': 'apple', 'type': 'fruit'}, {'tag': 'carrot', 'type': 'vegetable'}]

我想返回一个包含每个名为“tag”的元素的数组。例如:

['apple', 'carrot']

此外,我还希望能够对数组进行分区(即[25:50])。但我想如果有人能解决上述问题我就能弄清楚。

谢谢!

~小布

最佳答案

I have an array (or list) filled with subarrays with named indices.

您在 Python 中有一个列表,其中包含 dict 作为元素。

I want to return an array that contains each element named 'tag.'

您可以使用list comprehension在Python中。我们还需要检查字典中是否存在某个键。尝试以下代码:

li = [{'tag': 'apple', 'type': 'fruit'}, {'tag': 'carrot', 'type': 'vegetable'}]
result = [i['tag'] for i in li if 'tag' in i]
print(result)

输出:

['apple', 'carrot']

另一种方法:

result = []
for i in li:
if 'tag' in i:
result.append(i['tag'])
print(result)

Furthermore, I'd like to be able to section the array as well (i.e. [25:50]). But I think I could figure that out if somebody has the solution to the above problem.

我认为你的意思是切片。阅读 this了解更多信息。

关于Python列出数组中每个元素的命名索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59554258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com