我是编程的全新手,我正在学习Python。我写的是:
list = ["de", "sandy", "ger"]
我希望少于4个单词的元素进入名为newList
的新列表。请帮忙。到目前为止我已经这样做了:
list= ["de", "sandy", "ger"]
newlist =[]
for name in list:
if len(name) <4:
print name
newlist.append(name[0:3])
print newlist
这只为我提供了一个元素。
答案 0 :(得分:1)
打印物品并不会将其附加到其他任何地方。
list = ["de", "sandy", "ger"]
newlist = []
for name in list:
if len(name) < 4:
newlist.append(name)
print newlist
不执行此操作:
newlist.append(name[0:3])
这是使用for
循环的最后一个结果,这会导致不必要的行为。这意味着&#34;从for循环的最后一个处理值中取出前3个字符,并将其附加到空的新列表&#34;。