列表解析以拆分字符串并返回字符串及其长度

时间:2019-08-18 12:00:22

标签: python-3.x list tuples list-comprehension

我有一个字符串,我希望使用列表推导通过在列表推导中使用元组(单词,长度)来打印偶数个字母的单词。我尝试过类似的操作,以返回包含偶数个字母的单词元组列表:

sentence = 'If you dont actually care about collecting all the strings in a list using a list comprehension doesnt make much sense'

word_with_even_letters = [(word,len(word)) in sentence.split() if len(word)==0]

实际结果:

  

文件“”,第2行       word_with_even_letters = [[len,word(len)== 0,如果len(word)== 0]                                                                                     ^   SyntaxError:语法无效

预期结果:列表word_with_even_letters应包含以下元组:

(If,2)
(dont,4)
(actually,8)
(care,4)
(collecting,10)
(in,2)
(list,4)
(doesnt,6)
(make,4)
(much,4)

3 个答案:

答案 0 :(得分:0)

缺少命令:

word_with_even_letters = [(word,len(word)) for word in sentence.split() if len(word)%2==0]

答案 1 :(得分:0)

您需要在列表理解中使用for语句,并检查数字是否甚至不测试n == 0,而是n % 2 == 0

sentence = 'If you dont actually care about collecting all the strings in a list using a list comprehension doesnt make much sense'

word_with_even_letters = [(word, len(word)) for word in sentence.split() if len(word) % 2 == 0]

print(word_with_even_letters)

输出:

[('If', 2), ('dont', 4), ('actually', 8), ('care', 4), ('collecting', 10), ('in', 2), ('list', 4), ('list', 4), ('doesnt', 6), ('make', 4), ('much', 4)]

答案 2 :(得分:0)

sentence.split()

是一个迭代,您必须使用其项目, 请将您的代码更改为此:

sentence = 'If you dont actually care about collecting all the strings in a list using a list comprehension doesnt make much sense'

word_with_even_letters = list((word,len(word)) for word in sentence.split() if len(word)%2==0)

print(word_with_even_letters)