python和列表比较

发布于 2025-02-03 04:39:33 字数 548 浏览 2 评论 0原文

list1 = ['bd 100bd has 15', 'bd 100abd has 0', 'bd 100bbd has 10', 'bd 100cbd has  0', 'bd 100dbd has 0']

list2 = ['100', '100a']

new_list = []
idx =0 

for item in list1:
    if any(x in line for x in list2):
        new_list.insert(list1)
        idx += 1

    
print(new_list)

我正在尝试打印一个将比较这两个列表的新列表,如果list1具有list2(即100)的字符串,它将打印字符串。

new_list = ['bd 100bd has 15', 'bd 100abd has 0']
list1 = ['bd 100bd has 15', 'bd 100abd has 0', 'bd 100bbd has 10', 'bd 100cbd has  0', 'bd 100dbd has 0']

list2 = ['100', '100a']

new_list = []
idx =0 

for item in list1:
    if any(x in line for x in list2):
        new_list.insert(list1)
        idx += 1

    
print(new_list)

I am trying to print a new list that will compare the two lists and if list1 has the string from list2 (i.e 100) it will print the string.

new_list = ['bd 100bd has 15', 'bd 100abd has 0']

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

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

发布评论

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

评论(2

静待花开 2025-02-10 04:39:33
result = []

for item_1 in list_1:
    for item_2 in list_2:
        if item_2 in item_1:
            if item_1 not in result:
                result.append(item_1)

print(len(result))
result = []

for item_1 in list_1:
    for item_2 in list_2:
        if item_2 in item_1:
            if item_1 not in result:
                result.append(item_1)

print(len(result))
不醒的梦 2025-02-10 04:39:33

如果您正在查看字符串是否等于与list1的字符串相等,则应该有效。如果您正在寻找它是否包含它,那么您的解决方案应该起作用。

for item in list1:
   if (item in list2 or item in list2):
       new_list.append(item)
       idx += 1

如果您在List1中有更多元素,请使用嵌套循环并检查 list2中的每个单独元素

If you are looking at if a string is EQUAL to a string from list1, this should work. If you are looking for if it contains it, then your solution should work.

for item in list1:
   if (item in list2 or item in list2):
       new_list.append(item)
       idx += 1

If you have more elements in list1, use a nested for loop and check for each individual element in list2

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