根据第三个列表中的随机项,从两个列表中选择一个随机项

时间:2015-03-25 16:17:24

标签: python list random reference

我正在尝试使用以下代码选择随机国家/地区的随机城市:

COUNTRIES= ["NL", "NO"]

NL = [
    "Assen", "Almere", "Leeuwarden", "Nijmegen", "Groningen", 
    "Maastricht", "Eindhoven", "Amsterdam", "Enschede", "Utrecht", 
    "Middelburg", "Rotterdam"
]

NO = [
    "Fredrikstad", "Baerum", "Oslo", "Ringsaker", "Gjovik", 
    "Drammen", "Sandefjord", "Skien", "Arendal", "Kristiansand", 
    "Stavanger", "Bergen", "Forde", "Alesund", "Trondheim", 
    "Stjordal", "Bodo", "Tromso", "Alta"
]

CHOSEN_CITY = random.choice(random.choice(COUNTRIES))

print CHOSEN_CITY

但是,这只能给我一个'L''O'N。我在这里做错了什么?

3 个答案:

答案 0 :(得分:6)

试试这个

random.choice(NL + NO)

答案 1 :(得分:4)

您选择的是一个随机国家/地区,然后从每个字符串中选择一个随机字母。这不是Python的工作原理。

更好的设置是将数据存储在字典中,如下所示。然后,您可以选择一个随机国家(通过在dict中选择一个随机键)。然后,您将使用该随机密钥选择随机城市。

import random

data = {
    'NL': ["Assen", "Almere", "Leeuwarden", "Nijmegen", "Groningen", "Maastricht", 
           "Eindhoven", "Amsterdam", "Enschede", "Utrecht", "Middelburg", "Rotterdam"],
    'NO': ["Fredrikstad", "Baerum", "Oslo", "Ringsaker", "Gjovik", "Drammen",
           "Sandefjord", "Skien", "Arendal", "Kristiansand", "Stavanger", "Bergen", 
           "Forde", "Alesund", "Trondheim", "Stjordal", "Bodo", "Tromso", "Alta"]
}

random_country = random.choice(list(data.keys()))
random_city = random.choice(data[random_country])

print(random_country, random_city)
# NO Drammen

答案 2 :(得分:2)

这不是Python的工作方式!一个列表中的字符串不是对另一个变量的引用,即使它们共享相同的名称。

NL = ["Assen", "Almere", "Leeuwarden"]  # truncated for clarity
NO = ["Fredrikstad", "Baerum", "Oslo"]

countries = [NL, NO]  # refer to variables, not just strings
chosen_city = random.choice(random.choice(countries))

print(chosen_city)

应该有效。只需从两个附加列表中选择就更清楚了,但在您的特定情况下可能无效。