如何检查列表中的字符串是否在另一个列表中?

发布于 2024-12-11 11:53:45 字数 156 浏览 0 评论 0原文

假设我有 2 个列表:

a=['LOL','GG','rofl']
b=['5 KEK muh bobo LOL', 'LOL KEK bobo bobo GG']

如何检查 a 中的第一个元素是否可以在 b 的第一个元素中找到?

Lets say i have 2 lists:

a=['LOL','GG','rofl']
b=['5 KEK muh bobo LOL', 'LOL KEK bobo bobo GG']

How do i check if first element in a can found in first element of b?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

×眷恋的温暖 2024-12-18 11:53:45

只是这样:

a[0] in b[0] # will return True or False

也许您想检查所有这些:

set(i for i in a for j in b if i in j)

或者

{i for i in a for j in b if i in j} #Python 2.7+

Just that:

a[0] in b[0] # will return True or False

maybe you want to check all of them:

set(i for i in a for j in b if i in j)

or

{i for i in a for j in b if i in j} #Python 2.7+
我们只是彼此的过ke 2024-12-18 11:53:45

Python实际上非常健壮。你就可以做。

a[0] in b[0]

Python is actually very robust. You can just do.

a[0] in b[0]
鯉魚旗 2024-12-18 11:53:45

如果您只需要知道它是否在字符串中:

if a[0] in b[0]: pass

但是,上面的问题是这两者都会返回 true:

if "LOL" in "a b LOL c": pass
if "LOL" in "a b xxLOLxx c": pass

因此,如果您关心单词与简单的存在,只要您的分隔符一致:

if a[0] in b[0].split(" "): pass

如果您需要知道哪个单词位置:

idx = b[0].split().index(a[0]) # note, throws a ValueError if not in the list

如果您需要知道字符串中的位置:

idx = b[0].find(a[0]) # returns -1 if not found

如果您想知道 a 中的每个元素是否在 b 的相应元素中(忽略任一列表上的额外条目):

[(i[0] in i[1]) for i in zip(a, b)] # to check for simple membership
[(i[0] in i[1].split()) for i in zip(a, b)] # to check for whole words

If you only need to know if it's in the string or not:

if a[0] in b[0]: pass

However, the above has the problem that both of these will return true:

if "LOL" in "a b LOL c": pass
if "LOL" in "a b xxLOLxx c": pass

So if you care about words vs. simple presence, as long as your delimiters are consistent:

if a[0] in b[0].split(" "): pass

If you need to know which word position:

idx = b[0].split().index(a[0]) # note, throws a ValueError if not in the list

If you need to know the position in the string:

idx = b[0].find(a[0]) # returns -1 if not found

If you want to know if each element from a is in the corresponding element of b (ignores extra entries on either list):

[(i[0] in i[1]) for i in zip(a, b)] # to check for simple membership
[(i[0] in i[1].split()) for i in zip(a, b)] # to check for whole words
生生漫 2024-12-18 11:53:45

你可以简单地这样做:

a[0] in b[0]

如果a的第一个元素可以在b的第一个元素中找到,则返回True,否则返回False。

You can simply do:

a[0] in b[0]

which will return a True if the first element of a can be found in the first element of b, otherwise it will return False.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文