简体   繁体   English

使用枚举

[英]Working with enumerate

So I've just started with python the last few days with nothing but some basic coding knowledge from 5 years ago. 所以我在最近几天开始使用python,除了5年前的一些基本编码知识。 I'm in love. 我恋爱了。

I'm importing a .csv which contains historical alliances sorted by dyad...so each alliance has a special number. 我正在导入.csv,其中包含按dyad排序的历史联盟...所以每个联盟都有一个特殊号码。 There are many more in the file with the same country. 同一个国家/地区的文件中还有更多内容。 I'm trying to have a user give a country and a date and be able to return the countries they were in alliance with that year. 我正在努力让用户提供一个国家和一个日期,并能够返回他们与那一年结盟的国家。 Here's a row of data. 这是一排数据。

6 200 United Kingdom 255 Germany 1 1 1816 31 10 1822 1 0 1 0 0  1 0
6 200 United Kingdom 300 Austria-Hungary 1 1 1816 31 10 1822 1 0 1 0 0 1 0

First number is the dyad num, then country code and country, country code and country, day of alliance beginning, month, year, day of end, month, year. 第一个数字是二元数字,然后是国家代码和国家,国家代码和国家,联盟开始日,月,年,结束日,月,年。 Last parts aren't really important. 最后的部分并不重要。

import csv
name='United Kingdom'
diad = [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ']
with open('list.csv') as inputfile:
    r = list(csv.reader(inputfile))
    for i, j in enumerate(r):
         if j == name:
              diad[0]=name
          print "true"
              diad.insert(0, name)

I run it and get nothing, so the if statement isn't true... I don't understand how though. 我运行它什么也没得到,所以if语句不是真的......我不明白怎么回事。 You're looking at the first two lines of data, shouldn't enumerate find any instance of "United Kingdom" and insert what it found into the diad list? 您正在查看前两行数据,不应该枚举查找“英国”的任何实例并将其找到的内容插入到diad列表中? If I can make this piece work my task should be easy. 如果我能让这件作品完成,我的任务应该很简单。

Iterating through a CSV iterates through the rows , not the columns. 迭代通过CSV迭代而不是列。 So in each iteration, j is a list of columns. 所以在每次迭代中, j都是列的列表。 You'd then need to iterate through the elements in j as well, in order to compare against your string. 然后,您需要遍历j的元素,以便与您的字符串进行比较。

I think you're confused about what enumerate does. 我认为你对enumerate内容感到困惑。 You don't need it here at all, in fact. 事实上,你根本不需要它。 What it does is give you an index along with the value of the thing you're enumerating. 它的作用是给你一个索引以及你要枚举的东西的值。 So in this case, you'd get on the first iteration 0 plus the first row, then 1 with the second row, and so on. 因此,在这种情况下,您将进行第一次迭代0加上第一行,然后是第二行,依此类推。 Since you're not using the index, you don't want to use enumerate. 由于您没有使用索引,因此您不想使用枚举。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM