在枚举时,是否可以将单个值列表(例如[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)
答案 0 :(得分:1)
查看你的代码......我不确定它应该做什么,但我可以做一些猜测。
首先你选择一个随机词。然后,您查找与该单词匹配的所有单词的索引。然后,您希望将该索引列表与pop
一起使用。
好吧,你可以修复:
for idx in reversed(selected_word):
words.pop(idx)
(reversed
很重要,所以你先弹出最右边的那个。)
但是没有必要这样做,因为word_1
中应该只有words
的一个副本,因此selected_word
中只有一个索引。所以你可以这样做:
words.pop(selected_word[0])
但在这种情况下,理解是不必要的。获得所有匹配并获得第一个匹配与第一个匹配相同,并且列表已经有了一个方法: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)
答案 1 :(得分:0)
可能你想要这个(不删除任何单词)?:
Buffers: shared hit=2806
选择>>> 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