3 回答
TA贡献1893条经验 获得超10个赞
您可以将列表复制到一个新列表,而不是每次都遍历列表并用“/”分割
input_tuples = [('jay', 'other'), ('blah', 'other stuff')]
list_strings = ['blah', 'foo', 'bar', 'jay/day']
# Using a set as @Patrick Haugh suggested for faster look up
new_strings = {x.split('/')[0] for x in list_strings}
for tup in input_tuples:
if tup[0] in new_strings:
print('found', tup[0])
# outputs found jay, found blah
TA贡献1853条经验 获得超9个赞
选择传统的循环方式。这将元组中的名称与 lst 中的名称匹配:
lst = ['blah', 'foo', 'bar', 'jay/day']
tupl = ('unknown', 'bar', 'foo', 'jay', 'anonymous', 'ja', 'day')
for x in tupl:
for y in lst:
if x == y.split('/')[0]:
print(x, y)
# bar bar
# foo foo
# jay jay/day
TA贡献1783条经验 获得超4个赞
使用正则表达式:
import re
l = ['blah', 'foo', 'bar', 'jay/day']
def match(name, l):
for each in l:
if re.match("^{}(\/|$)".format(name), each):
return True # each if you want the string
return False
结果:
match('ja', l) # False
match('jay', l) # True
match('foo', l) # True
使用元组:
tupl = ('unknown', 'bar', 'foo', 'jay', 'anonymous', 'ja')
res = [match(x, l) for x in tupl]
资源:
[False, True, True, True, False, False]
添加回答
举报