我一直在寻找,但我找不到任何描述我问题的东西。我只是在学习python,所以我甚至不知道如何正确地表达这个问题。
我试图随机选择一些已定义的变量,但我无法弄清楚如何检索这些变量。例如:
import random
user1 = "usernamehere1"
userkey1 = "3097fds09aj4023jr30mf2ag2"
user2 = "usernamehere2"
userkey2 = "09asfh34907fsenk32498fgg9"
user3 = "usernamehere3"
userkey3 = "234kn34bnero8wn34lnkjwi34"
numbers = ["1", "2", "3"]
user_number = random.choice(numbers)
user = "user" + user_number
wif = "userkey" + user_number
print(user)
print(wif)
而不是:(如果它选择" 2"作为随机数):
我得到:
我猜错了什么?
答案 0 :(得分:1)
查看这篇文章To convert string to variable name,您可以使用exec将字符串更改为变量,但这不安全,绝对不建议使用。正如这里的帖子所解释的那样,您应该使用词典代替users["user" + user_number]
import random
user1 = "usernamehere1"
userkey1 = "3097fds09aj4023jr30mf2ag2"
user2 = "usernamehere2"
userkey2 = "09asfh34907fsenk32498fgg9"
user3 = "usernamehere3"
userkey3 = "234kn34bnero8wn34lnkjwi34"
dict = {}
dict[user1] = userkey1
dict[user2] = userkey2
dict[user3] = userkey3
numbers = ["1", "2", "3"]
user_number = random.choice(numbers)
user = "user" + user_number
print(user)
print(dict[user])
答案 1 :(得分:0)
评论是正确的,我只是想分享一种方法来实现它们。您可以将字典视为“查找表”,您可以在其中指定键 - >值对。有很多信息here
import random
users = {"1":"usernamehere1",
"2":"usernamehere2",
"3":"usernamehere3"}
keys = {"1":"3097fds09aj4023jr30mf2ag2",
"2":"09asfh34907fsenk32498fgg9",
"3":"234kn34bnero8wn34lnkjwi34"}
numbers = ["1", "2", "3"]
user_number = random.choice(numbers)
user = "user" + users[user_number]
wif = "userkey" + keys[user_number]
print(user)
print(wif)
答案 2 :(得分:0)
import random
users = [
{
'user':"usernamehere1",
'userkey':"3097fds09aj4023jr30mf2ag2"
},
{
'user':"usernamehere2",
'userkey':"09asfh34907fsenk32498fgg9"
},
{
'user':"usernamehere3",
'userkey':"234kn34bnero8wn34lnkjwi34"
}
]
user_number = random.choice(range(1,len(users)))
print(users[user_number]['user'])
print(users[user_number]['userkey'])
答案 3 :(得分:0)
您可以只使用一个字典:
import random
users = {
"usernamehere1": "3097fds09aj4023jr30mf2ag2",
"usernamehere2": "09asfh34907fsenk32498fgg9",
"usernamehere3": "234kn34bnero8wn34lnkjwi34"
}
user = random.sample(users.keys(), 1)
print(user[0])
print(users[user[0]])