[英]matching more than one substring in a list of strings
我有一個字符串列表:
mylist = ['room.ax','room-ax1232upper.bin','room-ki9e0lower.bin','window-rm-down.ax','window-rm-up.ax']
我想遍歷此列表並檢查 2 個或更多位置的字符串,以確保執行正確的 function。
例如(偽代碼):
for item in mylist:
if item contains 'room' with extension '.ax':
call_f1()
elif item contains 'room' and also 'upper' and with extension '.bin':
call_f2()
elif item contains 'room' and also 'lower' and with extension '.bin':
call_f3()
elif item contains 'window' and also 'down' and with extension '.ax':
call_f4()
如果我正在檢查單個 substring 那么它非常簡單:
for item in mylist:
if 'room' in item:
call_f()
但我不知道如何為多個子字符串執行此操作。
嘗試:
for item in mylist:
if 'room' in item and item.endswith('.ax'):
call_f1()
elif 'room' in item and 'upper' in item and item.endswith('.bin'):
call_f2()
elif 'room' in item and 'lower' in item and item.endswith('.bin'):
call_f3()
elif 'window' in item and 'down' in item and item.endswith('.ax'):
call_f4()
這行得通。
for item in mylist:
item = item.split('.')
if item[0] == 'room' and item[1] == 'ax':
print('room.ax if')
elif all(i in item[0] for i in ['room','upper']) == True and item[1] == 'bin':
print('roomupper.bin if')
elif all(i in item[0] for i in ['room','lower']) == True and item[1] == 'bin':
print('roomlower.ax if')
elif all(i in item[0] for i in ['window','down']) == True and item[1] == 'ax':
print('windowdown.ax if')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.