在Python中隐藏CSV文件中的列

2024-10-01 17:27:11 发布

您现在位置:Python中文网/ 问答频道 /正文

此源代码的目标是只打印国家人口和国家名称。我对Python还比较陌生,使用CSV和数据库,但有人告诉我,in a code review将数据存储在CSV中会更好。在

解决了:还有另一个问题。当你要求一个国家时,不管你输入的是正确的还是错误的,它仍然认为它不在列表中。在

源代码:

import random
import csv

print '\nCountries to choose from are\n'
country_list = []

with open('countries.csv', 'rb') as csvfile:
    countryreader = csv.reader(csvfile, delimiter=',', quotechar='|')
    for idx, country in enumerate(countryreader):
        print ' '.join(country) # everything besides population and country title should be hidden
        if (idx != 0): # Don't append the fist row (column headers)
            country_list.append(country[0])

startcountry = raw_input('\nWhat country would you like to start in? If you can\'t think of one, you can enter random to choose a random country.').title()

if startcountry == 'Random': # random.sample can be used for more than one country later on
    startcountry = random.choice(country_list)

while startcountry not in country_list:
    startcountry = raw_input('We don\'t know that country. Please enter one from the list above. ')

CSV文件:

^{pr2}$

Tags: csvtoinimportyou源代码random国家
1条回答
网友
1楼 · 发布于 2024-10-01 17:27:11

这是因为您使用空格作为分隔符,而csv文件使用逗号作为分隔符。在

改变

countryreader = csv.reader(csvfile, delimiter=' ', quotechar='|')

^{pr2}$

总之,我认为您使用了错误的数据结构,如果您read your CSV file to a dictionary,那么您可以轻松地访问国家名称和人口。在

相关问题 更多 >

    热门问题