gpt4 book ai didi

python - 编辑列表,同时将其与另一个列表作为约束进行比较

转载 作者:行者123 更新时间:2023-12-01 04:20:53 24 4
gpt4 key购买 nike

我有一个包含一些文字的列表,另一个列表中仅包含所需的文字,我想获得包含相关文字及其符号的输出,我应该如何计算这个输出?非常感谢

list=[0,-1, 2, 3, 11, 12, -13, 21, -22, 23, 31, -32, 33, 50, 20, 30]

needed literals = [11, 12, 13, 21, 22, 23, 31, 32, 33]

output = [11, 12, -13, 21, -22, 23, 31, -32, 33]

编辑:每个文字也是一个字符串,例如:'11'、'-12'等。

最佳答案

通过列表理解这很容易:

literal_list = [0, -1, 2, 3, 11, 12, -13, 21, -22, 23, 31, -32, 33, 50, 20, 30]
needed_literals = [11, 12, 13, 21, 22, 23, 31, 32, 33]
output = [n for n in literal_list if abs(n) in needed_literals]
#=> [11, 12, -13, 21, -22, 23, 31, -32, 33]

如果两个列表的元素都是字符串而不是整数,可以在条件中进行转换:

output = [n for n in literal_list if str(abs(int(n))) in needed_literals]

关于python - 编辑列表,同时将其与另一个列表作为约束进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33708547/

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