簡體   English   中英

將單個值列表索引轉換為Python中的整數?

[英]Single value list index into integer in Python?

枚舉時是否可以將單個值列表(例如[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)

查看您的代碼...我不確定它應該做什么,但是我可以做出一些猜測。

首先,您選擇一個隨機單詞。 然后,您查找與該單詞匹配的所有單詞的索引。 然后,您想將該索引列表與pop一起使用。

好吧,您可以解決此問題:

for idx in reversed(selected_word):
    words.pop(idx)

reversed很重要,因此您首先彈出最右邊的。)

但有沒有必要的,因為應該永遠只能是一個副本word_1words ,和因此只有一個索引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)

您可能想要這個(不刪除任何單詞)嗎?:

>>> 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_word

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM