我正在创建一个刽子手游戏,其中我有一个包含5个秘密单词的列表,以及从文本文件中读取的每个单词的提示:
list = ['word1', 'hint1', 'word2', 'hint2','word3', 'hint3','word4', 'hint4','word5', 'hint5']
我需要创建两个单独的列表,分别只包含秘密字和提示。我该怎么做呢?
期望的结果:
words = ['word1','word2','word3','word4','word5']
hints = ['hint1','hint2','hint3','hint4','hint5']
答案 0 :(得分:5)
使用切片和步骤符号生成两个列表,l[::2]
将从第一个元素开始执行2个元素,而l[1::2]
也将从第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详细解释了这个