【问题标题】:Why does my code give me a single value rather than a list为什么我的代码给我一个值而不是一个列表
【发布时间】:2019-04-03 15:00:35
【问题描述】:

我一直在处理一些 CSV 文件,我是一个初学者,但我觉得我已经掌握了它,虽然我不明白为什么当我尝试打印出我的 csv 文件中的第二列时,python 打印输出单个值,而不是第二列中所有值的列表(它们都将是 2018-01,因为该列在整个表格中都是相同的)。

我的印象是我的代码将列拆分为每行的单独列表,因此如果我想打印sep[1],我将获得每行第二列的值。虽然目前sep[1] 给了我一个单一的价值。

这是我的代码

with open('2018-01-btp-street.csv', 'r') as file:
    for row in file:
        sep = row.split(',')


print (sep[1])!

这是 csv 文件的图片https://i.stack.imgur.com/ijB1e.jpg

【问题讨论】:

  • ! 是干什么用的?
  • 抱歉打错了

标签: python list csv indexing


【解决方案1】:

每次循环新行时,您都会重置sep。假设文件有 2 行:

with open('2018-01-btp-street.csv', 'r') as file:
    for row in file:  # first loop: 
        sep = row.split(',')  # sep now contains all items in the first row that were separated by commas.
    #second loop: sep now only(!) contains all items in the SECOND row that were separated by commas.

您可以通过在循环内 sep 的定义之后添加 print(sep) 来测试这一点。

现在,您需要的是每行的第二列。 string.split(other_string)返回由other_string 分隔的字符串的所有单独片段的列表。因此,您可以将这些列表中的每一个都存储在一个新列表中,如下所示:

all_values = []
with open('2018-01-btp-street.csv', 'r') as file:
    for row in file:
        sep = row.split(',')
        all_values.append(sep)  # this is the important part. sep will still be reset every loop, but the values are now stored in all_values.

现在,您有一个列表列表。要获取所有列表的第二个值,请执行

for l in all_values:
    print(l[1])

你也可以使用 list comprehension 来做同样的事情:

with open('2018-01-btp-street.csv', 'r') as file:
     all_values = [row.split(',') for row in file]

all_values 看起来像这样:

[[row1_col1, row1_col2, row1_col3, ...], [row2_col1, row2_col2, row2_col3,...], ...]

或者,获取所有列的列表:

with open('2018-01-btp-street.csv', 'r') as file:
     all_values = [row.split(',') for row in file]
all_columns = [[l[i] for l in all_values] for i in range(len(all_values[0]))] 

这会给你一个看起来像的列表

[[row1_col1, row2_col1, row3_col1], [row1_col2, row2_col2, row3_col2], ...]

现在你可以使用

print(all_columns[1])

获取第二列的所有值。

【讨论】:

  • 很好的答案,所以只是为了确保我已经正确理解了这一点,打印 sep[1] 仅朋友列表的一部分而不是我期望的列表列表的原因是因为 row.split为我的文件中使用的所有字符串创建一个列表,列表中的每个单独元素用逗号分隔?因为我在 for 循环中使用了 sep,所以它最终会迭代,从而将每一行中的每个值都组合到一个列表中?
  • 那种。您遍历文件中的所有行。在每个循环中使用 split 会返回该行所有单独片段的列表,在所有有逗号的地方分隔。您将sep 定义为该列表的副本,但您在for 循环的每次迭代中为每一行再次重新定义它。所以最后seplast_row.split (',')基本一样,只有最后一行。所以它是一个字符串列表,因此sep[1] 只是一个字符串。
【解决方案2】:

在您的代码中,file 是一个“类文件”对象。遍历它会在每次迭代时为您提供字符串,因此 row 是一个字符串。

调用row.split() 会返回一个列表。所以sep 是一个字符串列表。所以sep[1]确实应该是一个字符串。

csvpandas 之类的 Python 库具有列抽象和使用列,但在这种情况下,您不会拥有这些。

您的代码示例末尾的! 对我来说看起来不正确。

【讨论】:

    【解决方案3】:

    您表示要“列出第二列中的所有值”。在这种情况下,您需要在循环内执行print()...所以您需要缩进函数调用,使其位于循环内。

    with open('2018-01-btp-street.csv', 'r') as file:
        for row in file:
            sep = row.split(',')
            print (sep[1])
    

    您的初始代码运行循环,然后在循环完成后执行最后一个值的print()

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-07-25
      • 1970-01-01
      • 2016-09-18
      • 2018-05-15
      • 1970-01-01
      • 2021-06-09
      • 1970-01-01
      相关资源
      最近更新 更多