在python中,如何使用字符串元素在两个列表中循环使用条件

在python中,如何使用字符串元素在两个列表中循环使用条件,python,list-comprehension,Python,List Comprehension,例如,我有两个列表,如 a = ["there", "is", "a", "car"] b = ["i", "feel", "happy", "today"] 我想比较a[0]和b[0]1,如果在'there'和'I'之间有任何共同的字母,那么结果应该是真的,否则应该是假的 输出: [False,False,True,True] 如果它只是a和b中的一个元素,但不能遍历列表,我就可以这样做 a = ["there", "is", "a", "car" , "jill"] b = ["i",

例如,我有两个列表,如

a = ["there", "is", "a", "car"]
b = ["i", "feel", "happy", "today"]
我想比较
a[0]
b[0]1,如果在
'there'
'I'之间有任何共同的字母,那么结果应该是真的,否则应该是假的

输出:

[False,False,True,True]
如果它只是a和b中的一个元素,但不能遍历列表,我就可以这样做

a = ["there", "is", "a", "car" , "jill"]
b = ["i", "feel", "happy", "today" ,"jill"]
d = []
i = 0
for  word in range(len(a)):
    for word in range (len(b)):
        c = list(set(a[i]) & set(b[i]))
    if c == []:
            d.append(False)
    else:
            d.append(True)
i = i+1
print (d)

像这样的方法应该会奏效:

d = [len(set(i)&set(j)) > 0 for i,j in zip(a,b)]
测试:

>>> a = ["there", "is", "a", "car" , "jill"]
>>> b = ["i", "feel", "happy", "today" ,"jill"]
>>> d = [len(set(i)&set(j)) > 0 for i,j in zip(a,b)]
>>> d
[False, False, True, True, True]
>>> 

假设您希望成对执行测试,这是您的代码:

print([bool(set(x) & set(y)) for (x, y) in zip(a, b)])
您的输入列表长度不等,因此我不清楚您想用“吉尔”(如果a,则b项不匹配)做什么

更详细一点:

  • zip从一对列表生成一个对列表(它实际上从n个列表生成一个n元组列表,但在我们的示例中,n==2)
  • 如图所示,从字符串构造集将返回字符串中的字符集
  • &作为集合运算符设置为相交
  • 从集合构造bool值返回集合的非空性
  • 简单的列表理解构造结果

其他人的答案足够好,以下是您的版本:

a = ["there", "is", "a", "car" , "jill"]
b = ["i", "feel", "happy", "today" ,"jill"]
d = []
i = 0
for  word in range(len(a)):
    for word in range (len(b)):
        c = list(set(a[i]) & set(b[i]))
    if c == []:
            d.append(False)
    else:
            d.append(True)
    i = i+1  # <------------------------ this was missing an indentation
print (d)
a=[“那里”、“是”、“a”、“车”、“吉尔”]
b=[“我”、“感觉”、“快乐”、“今天”、“吉尔”]
d=[]
i=0
对于范围内的单词(len(a)):
对于范围内的字(len(b)):
c=列表(集合(a[i])和集合(b[i]))
如果c=[]:
d、 附加(假)
其他:
d、 追加(真)

i=i+1#既然问题已经得到回答,答案也已经投票表决,我相信接受答案或澄清为什么不能接受答案将是良好公民身份的证明。谢谢你提供的细节,阿米泰