列表列表和随机选择

lists of list and random choice

我需要帮助的问题是:

Write a program that stores the names of ten countries in column1 and their capitals in column2. The program should then pick a random country and ask the user for the capital.

Display an appropriate message to the user to show whether they are right or wrong.

到目前为止我有

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])

如果有人能帮忙的话。

你应该这样写:

listoflist = [column1, column2]

在您的代码中,您没有正确定义列表的列表,这会导致错误。

我认为您的列表设置列表与您的预期有些偏差。尝试这样的事情:

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!")
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")

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

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

与您最初的用户输入主题保持一致,逻辑运行良好,您可以使用 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!")