gpt4 book ai didi

python - 列表的交集,查找长度

转载 作者:行者123 更新时间:2023-11-30 23:13:02 24 4
gpt4 key购买 nike

如果我们正在寻找两个列表的交集,我们通常会这样做

b1 = set(aList).intersection(aList2)
print(b1)

但是如果我们只想得到两个长度为 4 的单词列表的交集怎么办?

例如。

所以如果

aList = ["james", "kobe", "ball"]

aList2 = ["jimmy","james","kobe"]

我希望 b1 = ["kobe"] 因为 kobe 的长度为 4,而 james 的长度不是

我们需要先从列表中取出所有长度为4的单词吗?或者有没有办法在交叉路口时进行检查?

最佳答案

您可以使用 comprehension为此:

four_letter_intersection = {
word for word in set(list_a).intersection(list_b) if len(word) == 4
}

关于python - 列表的交集,查找长度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29552827/

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