如果当前项目的索引0处的字符是字母“a”,则继续下一个字符。否则,打印出当前成员。
示例:["abc", "xyz"]
将只打印“xyz”。
def loopy(items):
for item in items:
if item[0] == "a":
continue
else:
print(items)
答案 0 :(得分:1)
filter
怎么样?
In [191]: print('\n'.join(filter(lambda x: x[0] != 'a', ["abc", "xyz", "test"])))
xyz
test
答案 1 :(得分:0)
几乎没有更正:
>>> l=['abi', 'crei', 'fci', 'anfe']
>>> def loopy(list):
... for i in list:
... if i[0]=='a':
... continue
... else:
... print i
...
>>> loopy(l)
crei
fci
你可以这样缩短:
>>> def loopy(list):
... for i in list:
... if i[0]!='a':
... print i
...
>>> loopy(l)
crei
fci
或以一行打印:
>>> def loopy3(list):
... for i in list:
... print i if i[0]!='a' else '',
...
>>> loopy3(l)
crei fci
但你也可以使用bogdanciobanu建议的列表理解:
>>> def loopy2(list):
... print [i for i in list if i[0]!='a']
>>> loopy2(l)
['crei', 'fci']
答案 2 :(得分:0)
def loopy(items):
for item in items:
if not item.startswith('a'):
print(item)