我有一個字串,我想在其中搜索是否有單詞。(多個字)
如何列印在字串中找到的單詞?
這是我的代碼:
MLB_team = {
'Colorado' : 'Rockies',
'Boston' : 'Red Sox',
'Minnesota': 'Twins',
'Milwaukee': 'France',
'Seattle' : 'Mariners'
}
def location():
mlb_str = str(MLB_team)
location = ["Cuba", "France", "USA"]
if any(x in mlb_str for x in location):
print("yes")
else:
print("no")
location()
現在它列印“是”,因為“法國”一詞在 Mlb _team 字串中。但我也想列印在字串中找到的單詞 ("France")
uj5u.com熱心網友回復:
您想使用回圈來訪問找到的確切元素。
for x in location:
if x in str(MLB_team):
print(x)
continue # if you only want the first
但是,我建議不要使用整個字典的字串,而是單獨回圈遍歷其鍵和值
for k, v in MLB_team.items():
for x in location:
if x in str(k):
print(k, x)
if x in str(v):
print(v, x)
uj5u.com熱心網友回復:
你可以這樣做:
MLB_team = {
'Colorado' : 'Rockies',
'Boston' : 'Red Sox',
'Minnesota': 'Twins',
'Milwaukee': 'France',
'Seattle' : 'Mariners'
}
def location():
mlb_str = str(MLB_team)
location = ["Cuba", "France", "USA"]
flag = False
for x in location:
if x in mlb_str:
print(x)
flag = True
if flag:
print("yes")
else:
print("no")
location()
uj5u.com熱心網友回復:
def location():
location = ["Cuba", "France", "USA"]
#1. get the dict keys and store in list
mlbkey_list = []
for x in MLB_team.keys():
mlbkey_list.append(x)
#2. repeat same for values
mlbvalues_list = []
for x in MLB_team.values():
mlbvalues_list.append(x)
#3. merge both lists
mainlist = mlbkey_list mlbvalues_list
#4. compare 2 lists
for x in location:
for y in mainlist:
if x == y:
print(f"Yes: {x}")
else:
print("No")
location()
uj5u.com熱心網友回復:
你可以有一個這樣的交集
def location():
location = ["Cuba", "France", "USA"]
my_set = {*MLB_team.keys(), *MLB_team.values()}
print(my_set.intersection(set(location)))
location()
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/341443.html
上一篇:R-高效插入多個字串
