是否可以在枚举单值列表(例如5)索引(例如4)时将其转换为整数?我正在尝试做一个程序,用给定的单词和数字创建一个随机的用户名,如果一个单词已经被使用过,我想删除它:
import random
# data (words/numbers)
words = ['Cool', 'Boring', 'Tall', 'Short']
numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
# words
word_1 = random.choice(words)
selected_word = [i for i,x in enumerate(words) if x == word_1]
words.pop(selected_word)
word_2 = random.choice(words)
# numbers
number_1 = random.choice(numbers)
number_2 = random.choice(numbers)
# printing username
print(word_1+word_2+number_1+number_2)发布于 2018-04-29 13:05:22
查看您的代码…我不确定它应该做什么,但我可以猜到一些。
首先,你选择一个随机单词。然后查找与该单词匹配的所有单词的索引。然后,您希望将该索引列表与pop一起使用。
好的,你可以解决这个问题:
for idx in reversed(selected_word):
words.pop(idx)( reversed很重要,所以您要先弹出最右边的。)
但是没有必要这样做,因为在words中应该只有一个word_1副本,因此在selected_word中也只有一个索引。所以你可以这样做:
words.pop(selected_word[0])但在这种情况下,理解是不必要的。获取所有匹配项并获取第一个匹配项所做的事情与获取第一个匹配项所做的事情相同,lists已经有了一个这样的方法:index。
words.pop(words.index(word_1))但实际上,您可以直接获取索引,而不是选择一个单词,然后查找它来获得索引:
index = random.randrange(len(words))
word_1 = words.pop(index)或者,最简单的是,只需将整个内容替换为:
word_1, word_2 = random.sample(words, 2)发布于 2018-04-29 13:12:16
也许你想要这个(不删除任何单词):
>>> import random
>>> words = ['Cool', 'Boring', 'Tall', 'Short']
>>> numbers = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
>>> selected_word_indices = set()
>>> def select_word():
if len(selected_word_indices) == len(words):
raise Exception("No More Unique Word Left")
while True:
chosen_index = random.randint(0,len(words)-1)
if chosen_index not in selected_word_indices:
chosen = words[chosen_index]
selected_word_indices.add(chosen_index)
return chosen
>>> word_1 = select_word()
>>> word_2 = select_word()
>>> number_1 = random.choice(numbers)
>>> number_2 = random.choice(numbers)
>>> print(word_1+word_2+number_1+number_2)使用del选择会更简单,但需要words的副本(如果您想要原始列表,words保持不变):
>>> words_copy = words.copy()
>>> def select_word():
if len(words_copy) == 0:
raise Exception("No More Unique Word Left")
chosen_index = random.randint(0,len(words_copy)-1)
chosen_word = words_copy[chosen_index]
del words_copy[chosen_index]
return chosen_wordhttps://stackoverflow.com/questions/50083493
复制相似问题