每当我运行此代码时,它只会给我一个空白列表,我想知道我做错了什么。我正在尝试打印长于n的单词列表。当我尝试运行更新的代码时,它只打印我输入的单词列表中的第一个单词。
def filterlongword(string,number):
for i in range(len(string)):
listwords = []
if len(string[i]) > number:
listwords.append(string[i])
return listwords
def main():
words = input("Please input the list of words: ")
integer = eval(input("Please input an integer: "))
words1 = filterlongword(words,integer)
print("The list of words greater than the integer is",words1)
main()
答案 0 :(得分:1)
listwords
listwords
def filterlongword(string,number):
listwords = []
for i in range(len(string)):
if len(string[i]) > number:
listwords.append(string[i])
return listwords
使用list comprehension的更好的版本:
def filterlongword(string,number):
return [word for word in string if len(word) > number]
要将输入字符串拆分为单词列表,请使用
words = input("Please input the list of words: ").split()
答案 1 :(得分:0)
更好的只是
def filterlongword(string,number):
return filter(lambda word:len(word)>number, string)
# or: return [w for w in string if len(w) > number]
答案 2 :(得分:0)
def listing(guess, number):
new_list = []
for i in range(len(guess)):
if len(guess[i]) > number:
new_list.append(guess[i])
print (new_list)
list1 = input("take input: ")
list = list1.split(",")
def main():
global list, integer1
integer = input()
integer1 = int(integer)
listing(list, integer1)
main()
**尝试此代码..这样可行,使用分隔符形成输入列表**
答案 3 :(得分:0)
您的主要问题是将单词作为单个字符串而不是可迭代的字符串传递。第二个问题是没有为缺少的.split指定单词之间的分隔符。这是我的版本。
我使longwords
成为一个生成器函数,因为在实际使用中,没有必要将长字序列作为列表,我在输出格式中给出了一个例子。
def longwords(wordlist, length):
return (word for word in wordlist if len(word) >= length)
def main():
words = input("Enter words, separated by spaces: ").split()
length = int(input("Minimum length of words to keep: "))
print("Words longer than {} are {}.".format(length,
', '.join(longwords(words, length))))
main()
这导致例如
Enter words, separated by spaces: a bb ccc dd eeee f ggggg
Minimum length of words to keep: 3
Words longer than 3 are ccc, eeee, ggggg.
答案 4 :(得分:0)
也许您可以将代码缩短为以下内容:
legend("topright", inset=.05, c("p(k)"), lty="solid", pch=21, col=c"black", pt.bg="red")
答案 5 :(得分:0)
content_divs
答案 6 :(得分:0)
尝试
***
def filter_long_words(n, words):
list_of_words=[]
a= words.split(" ")
for x in a:
if len(x)>n:
list_of_words.append(x)
return list_of_words
答案 7 :(得分:0)
LinkEntity
答案 8 :(得分:0)
def filter_long_words(lst,n):
a=[]
for i in lst:
if n<len(i):
a.append(i)
return a
答案 9 :(得分:-1)
过滤单词列表
def filter_long_words(lst,n):
return [word for word in lst if len(word)>n]