gpt4 book ai didi

python - 从一个列表返回索引范围以从另一个列表获取值

转载 作者:行者123 更新时间:2023-12-05 08:38:20 25 4
gpt4 key购买 nike

我有两个大小相等的列表,一个具有数据类型(连续出现):

types = ["vigi","vigi","fruits","fruits","fruits","nothing","nothing","nothing","nothing"]

第二个列表是关于数据的:

data = ["xx","tr","kl","ut","ew","uy","lp","eq","aq"]

从数据列表中,我知道 "xx","tr""vigi""kl","ut","ew"“水果” 等等。

我每次都需要将 data 分成两个数据集:

data1 = data[indices for type "vigi"]
data2 = data[indices for the remaining (i.e. data for "fruits" and "nothing")]

第二次会有:

data1 = data[indices for type "fruits"]
data2 = data[indices for the remaining (i.e. data for "vigi" and "nothing")]

等等..

请提供任何帮助。

最佳答案

你可以使用zip()函数:

types = ["vigi","vigi","fruits","fruits","fruits","nothing","nothing","nothing","nothing"]
data = ["xx","tr","kl","ut","ew","uy","lp","eq","aq"]


data1 = [d for t, d in zip(types, data) if t == 'vigi']
data2 = [d for t, d in zip(types, data) if t != 'vigi']

print(data1)
print(data2)

打印:

['xx', 'tr']
['kl', 'ut', 'ew', 'uy', 'lp', 'eq', 'aq']

其他版本(只遍历列表一次):

types = ["vigi","vigi","fruits","fruits","fruits","nothing","nothing","nothing","nothing"]
data = ["xx","tr","kl","ut","ew","uy","lp","eq","aq"]

data1, data2 = [], []
for t, d in zip(types, data):
if t == 'vigi':
data1.append(d)
else:
data2.append(d)

print(data1)
print(data2)

关于python - 从一个列表返回索引范围以从另一个列表获取值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63090351/

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