你有字符串,而不是整数,所以你必须先将它们转换为整数:
a_nums = [int(n) for n in a.split(',')]
b_nums = [int(n) for n in b.split(',')]
这使用list comprehension 将str.split() method 调用的每个结果转换为带有int() function 的整数。
要测试两个序列中是否有数字,您可以使用sets,然后测试是否有交集:
set(a_nums) & set(b_nums)
如果结果不为空,则序列之间存在共享数字。由于非空集 are considered 'true',在 Python 中,您可以使用 bool() 将其转换为布尔值:
bool(set(a_nums) & set(b_nums))
集合是迄今为止测试此类交叉点最有效的方法。
使用生成器表达式和set.intersection() method:
bool(set(int(n) for n in a.split(',')).intersection(int(n) for n in b.split(',')))
或者使用map() 函数可能更紧凑:
bool(set(map(int, a.split(','))).intersection(map(int, b.split(','))))
演示:
>>> a = "5, 7"
>>> b = "6,5"
>>> bool(set(map(int, a.split(','))).intersection(map(int, b.split(','))))
True
或将其分解一下:
>>> [int(n) for n in a.split(',')]
[5, 7]
>>> [int(n) for n in b.split(',')]
[6, 5]
>>> set(map(int, a.split(',')))
set([5, 7])
>>> set(map(int, a.split(','))).intersection(map(int, b.split(',')))
set([5])
>>> bool(set(map(int, a.split(','))).intersection(map(int, b.split(','))))
True