我有多个字符串,如下所示:
“BPBA-SG790-NGTP-W-AU-BUN-3Y”
我想将字符串与列表进行比较,如果字符串的一部分在列表中,我只想将列表中找到的部分作为新变量
这是我的代码:
mylist = ["770", "790", "1470", "1490"]
sq = “BPBA-SG790-NGTP-W-AU-BUN-3Y”
matching = [s for s in mylist if any(xs in s for xs in sq)]
print(matching)
>>> ['770', '790', '1470', '1490']
例如,这就是我想要得到的:
mylist = ["770", "790", "1470", "1490"]
sq = “BPBA-SG790-NGTP-W-AU-BUN-3Y”
matching = [s for s in mylist if any(xs in s for xs in sq)]
print(matching)
>>> 790
你知道怎么做吗
您可以使用python中的
in
关键字:代码遍历列表并打印列表元素(如果它在字符串中)
我不确定我是否理解你的问题,但下面的内容应该可以解决这个问题
它将返回字符串中出现的列表元素的列表
这样,您可以使用列表理解:
输出:
相关问题 更多 >
编程相关推荐