如何在Python中使用for循环创建列表列表?

2024-04-28 21:52:28 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我当前的列表:

wordOccur = ['tears', 1, 'go', 1, 'i', 4, 'you', 7, 'love', 2, 'when', 3]

我就是这样创建它的:

    wordOccur = []

    for x in keywords:

            count = words.count(x)

            wordOccur.append(x)

            wordOccur.append(count)

词语指的是字符串列表。每根弦都是一首诗中的单数词

我如何制作wordOccur = [['tears', 1], ['go', 1],[ 'i', 4],[ 'you', 7],[ 'love', 2],[ 'when', 3]]


Tags: 字符串inyougo列表forcountwhen
3条回答

您可以更改此代码

wordOccur = []

for x in keywords:
  count = words.count(x)
  wordOccur.append(x)
  wordOccur.append(count)

将其转换为此代码

wordOccur = [[word, keywords.count(word)] for word in keywords]

您可以使用一个简单的列表:

words = 'i love you. when you cry tears i cry. when i love you. you, you, you! when i go to you.'
keywords = ['tears', 'go', 'i', 'you', 'love', 'when']

wordOccur = [[w, words.count(w)] for w in keywords]

输出:

[['tears', 1], ['go', 1], ['i', 4], ['you', 7], ['love', 2], ['when', 3]]

不过,您可能会发现字典更有用:

wordOccur = { w : words.count(w) for w in keywords }

输出:

{'i': 4, 'tears': 1, 'go': 1, 'love': 2, 'when': 3, 'you': 7}

实际上,您是在附加元素而不是列表。使用计数器

from collections import Counter
d = Counter(keywords)
[[word,d.get(word,0)] for word in set(keywords)] # use set here to remove the duplicates but will not conserve the order

下面是一个解决方案,它可以在代码后面直接假定wordOccur = ['tears', 1, 'go', 1, 'i', 4, 'you', 7, 'love', 2, 'when', 3]

random_iterator = iter(wordOccur)
[[next(random_iterator),next(random_iterator)] for i in range(len(wordOccur)//2)]

输出

[['tears', 1], ['go', 1], ['i', 4], ['you', 7], ['love', 2], ['when', 3]]

相关问题 更多 >