仅限字符F:
sportslist = ["Football" , "Fencing" , "Cricket" , "Basketball" , "Baseball" , "Tennis"]
newl = []
for word in sportslist:
if word.startswith('F'):
newl.append(word)
print (newl)输出:
['Football'] , ['Fencing'] 我使用for循环明显地重复了编码,但是由于某些原因,当我尝试打印以另一个字母开头的多个单词时,假设我想打印以F和B开头的单词。当我得到一个空白输出时,我该如何执行它呢?
发布于 2020-12-16 08:29:05
您可以使用
.startswith()方法的参数),(而不是使用if语句和.append()方法的for循环):
sportslist = ["Football" , "Fencing" , "Cricket" , "Basketball" , "Baseball" , "Tennis"]
newl = [word for word in sportslist if word.startswith(("F", "B"))]
print(newl)‘足球’,‘击剑’,‘篮球’,‘棒球’
注意:
我在列表理解中添加了多余的空格,以强调它的3个部分:
word -要添加到目标列表中的内容,for word in sportslist -其中if word.startswith(("F", "B"))是点1中的满足。迭代获得,word -条件必须从点2开始满足。word。发布于 2020-12-16 08:08:48
您可以执行一个or并为B应用另一个startswith,这将会起作用:
for word in eustates:
if word.startswith('F') or word.startswith('B'):
newl.append(word)
print (newl)或者你可以试试:
for word in eustates:
if word[:1] in 'BF':
newl.append(word)
print (newl)或者:
for word in eustates:
if 'BF'.__contains__(word[:1]):
newl.append(word)
print (newl)发布于 2020-12-16 08:34:25
您可以使用元组('F', 'B')作为.startswith()方法的参数,并更正代码最后一行的缩进:
sportslist = ["Football" , "Fencing" , "Cricket" , "Basketball" , "Baseball" , "Tennis"]
newl = []
for word in sportslist:
if word.startswith(('F', 'B')):
newl.append(word)
print (newl) # <------------ no indentation!https://stackoverflow.com/questions/65315464
复制相似问题