列表和随机选择

时间:2015-01-10 19:06:34

标签: python list

我需要帮助的问题是:

  

编写一个程序,在column1中存储十个国家/地区的名称,在第二列中存储其大写字母。然后该程序应该选择一个随机的国家并向用户询问资金。

     

向用户显示适当的消息,以显示他们是对还是错。

到目前为止我已经

column1 = []
column2 = []

listoflist = [(column1)(column2)]
maxlength = 10

while len (column1) < maxlength:
    country = input("please enter a country: ")
    capital = input("please enter the capital of the country entered: ")
    column1.append(country)
    column2.append(capital)

for item in done:
    print (item[0],item[1])

如果有人可以帮忙请。

4 个答案:

答案 0 :(得分:1)

我相信你的列表设置列表有点偏离你的意图。尝试这样的事情:

from random import shuffle
data = []
maxlength = 10

while len (data) < maxlength:
    country = input("please enter a country: ")
    capital = input("please enter the capital of the country entered: ")

    # for this scenario, probably better to keep rows together instead of columns.
    data.append((country, capital)) # using a tuple here. It's like an array, but immutable.

# this will make them come out in a random order!
shuffle(data)

for i in range(maxlength):
    country = data[i][0]
    capital = data[i][1]
    print("Capital for the country {0}?".format(country))
    user_said_capital_was = input("What do you think?")
    if user_said_capital_was == capital:
        print("Correct!")
    else: 
        print("Incorrect!")

答案 1 :(得分:0)

你应该把它写成:

listoflist = [column1, column2]

在您的代码中,您未正确定义列表列表并导致错误。

答案 2 :(得分:0)

import random
dict1 ={"Turkey":"Istanbul","Canada":"Ottawa","China":"Beijing"}
list1=[key for key in dict1.keys()]
try:
    q=random.choice(list1)
except:
    print ("We are out of countries, sorry!")

while True:
    user=input("What is the capital city of {} ?: ".format(q))
    if user == dict1[q]:
        print ("Correct")
        list1.remove(q) #removing first choice so same country never asking again
        try:
            q=random.choice(list1)
        except:
            print ("We are out of countries,sorry!")
            break
    else:
        print ("Not correct")

使用dict和键值系统以及列表理解。

答案 3 :(得分:0)

列表列表可以工作,但是具有键值对的字典对此非常有用。

与用户输入的原始主题保持一致,逻辑运行良好,您可以使用random.choice功能选择您的国家,同时保持跟踪。

import random
data = {}
maxlength = 10

for _ in range(maxlength):
    country = input("please enter a country: ")
    capital = input("please enter the capital of the country entered: ")

    # using a dict, keeps things simple
    data[country] = capital

countries = list(data.keys())

picked = []
while len(picked) < maxlength:
    country = random.choice(countries)
    if country in picked:
        continue
    print("Capital for the country {0}?".format(country))
    user_said_capital_was = input("What do you think? ")
    if user_said_capital_was == data[country]:
        print("Correct!")
        picked.append(country)
    else: 
        print("Incorrect!")