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]
添加回答
舉報