首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在Python中将单值列表索引转换为整数?

问在Python中将单值列表索引转换为整数?
EN

Stack Overflow用户
提问于 2018-04-29 12:52:01
回答 2查看 904关注 0票数 0

是否可以在枚举单值列表(例如5)索引(例如4)时将其转换为整数?我正在尝试做一个程序,用给定的单词和数字创建一个随机的用户名,如果一个单词已经被使用过,我想删除它:

代码语言:javascript
复制
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)
EN

回答 2

Stack Overflow用户

发布于 2018-04-29 13:05:22

查看您的代码…我不确定它应该做什么,但我可以猜到一些。

首先,你选择一个随机单词。然后查找与该单词匹配的所有单词的索引。然后,您希望将该索引列表与pop一起使用。

好的,你可以解决这个问题:

代码语言:javascript
复制
for idx in reversed(selected_word):
    words.pop(idx)

( reversed很重要,所以您要先弹出最右边的。)

但是没有必要这样做,因为在words中应该只有一个word_1副本,因此在selected_word中也只有一个索引。所以你可以这样做:

代码语言:javascript
复制
words.pop(selected_word[0])

但在这种情况下,理解是不必要的。获取所有匹配项并获取第一个匹配项所做的事情与获取第一个匹配项所做的事情相同,lists已经有了一个这样的方法:index。

代码语言:javascript
复制
words.pop(words.index(word_1))

但实际上,您可以直接获取索引,而不是选择一个单词,然后查找它来获得索引:

代码语言:javascript
复制
index = random.randrange(len(words))
word_1 = words.pop(index)

或者,最简单的是,只需将整个内容替换为:

代码语言:javascript
复制
word_1, word_2 = random.sample(words, 2)
票数 1
EN

Stack Overflow用户

发布于 2018-04-29 13:12:16

也许你想要这个(不删除任何单词):

代码语言:javascript
复制
>>> 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保持不变):

代码语言:javascript
复制
>>> 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_word
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/50083493

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档