从列表中的特定范围中选择随机元素 - python
Selecting a random element from a certain range in a list - python
我正在创建一个刽子手游戏,其中有一个列表,其中包含 5 个秘密单词和从文本文件中读取的每个单词的提示:
list = ['word1', 'hint1', 'word2', 'hint2','word3', 'hint3','word4', 'hint4','word5', 'hint5']
我需要创建两个单独的列表,分别只包含密语和提示。我该怎么做呢?
期望的结果:
words = ['word1','word2','word3','word4','word5']
hints = ['hint1','hint2','hint3','hint4','hint5']
使用切片和步进符号生成两个列表,l[::2]
将从第一个元素开始步进 2 个元素,而 l[1::2]
也会步进 2 个元素但从第二个元素开始:
In [145]:
l = ['word1', 'hint1', 'word2', 'hint2','word3', 'hint3','word4', 'hint4','word5', 'hint5']
words = l[::2]
hints = l[1::2]
print(words)
print(hints)
['word1', 'word2', 'word3', 'word4', 'word5']
['hint1', 'hint2', 'hint3', 'hint4', 'hint5']
docs对此有更多解释
我正在创建一个刽子手游戏,其中有一个列表,其中包含 5 个秘密单词和从文本文件中读取的每个单词的提示:
list = ['word1', 'hint1', 'word2', 'hint2','word3', 'hint3','word4', 'hint4','word5', 'hint5']
我需要创建两个单独的列表,分别只包含密语和提示。我该怎么做呢?
期望的结果:
words = ['word1','word2','word3','word4','word5']
hints = ['hint1','hint2','hint3','hint4','hint5']
使用切片和步进符号生成两个列表,l[::2]
将从第一个元素开始步进 2 个元素,而 l[1::2]
也会步进 2 个元素但从第二个元素开始:
In [145]:
l = ['word1', 'hint1', 'word2', 'hint2','word3', 'hint3','word4', 'hint4','word5', 'hint5']
words = l[::2]
hints = l[1::2]
print(words)
print(hints)
['word1', 'word2', 'word3', 'word4', 'word5']
['hint1', 'hint2', 'hint3', 'hint4', 'hint5']
docs对此有更多解释