gpt4 book ai didi

python - 类型错误子设置字符串列表 - Python 3

转载 作者:太空宇宙 更新时间:2023-11-04 11:14:12 25 4
gpt4 key购买 nike

我正在尝试从另一个列表中提取一个列表的子集,但我收到了一个TypeError

a = ('one', 'two', 'two', 'three', 'four', 'five', 'three', 'three', 'eight', 'nine', 'ten')
a = list(a)
b = ('two', 'three', 'eight', 'nine')
b = list(b)
c = [a[i] for i in b] # subsets list a for what's in list b

返回:

TypeError: list indices must be integers or slices, not str

我在找什么:

print(a)
('two', 'two', 'three', 'three', 'three', 'eight', 'nine')

最佳答案

a 中获取 b 中的项目:

c = [i for i in a if i in b]
print(c)

输出:

['two', 'two', 'three', 'three', 'three', 'eight', 'nine']

关于python - 类型错误子设置字符串列表 - Python 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57404528/

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