【问题标题】:Splitting a line from a file into different lists将文件中的一行拆分为不同的列表
【发布时间】:2014-11-02 20:37:43
【问题描述】:

我的程序应该从用户那里获取输入并读取名称为 input 的文件。读取的文件被保存到一个名为投资组合的字典中,然后我所要做的就是将投资组合中的每一行排序为键和值。

这是我的代码。

portfolio = {}
portfolio = file_read() #Reads the file through a function
if file_empty(portfolio) == True or None: #nevermind this, it works
    print "The file was not found."
else:
    print "The file has successfully been loaded"

for line in portfolio:
    elements = line.strip().split(",") #separate lists by comma
    print elements[0] #using this to check
    print elements[1] #if it works at all

所有这些都是打印第一行中的第一个字母,即 S。显然 elements[1] 应该是第二个字母,但 index 超出范围,请赐教可能出了什么问题。

谢谢。

【问题讨论】:

  • 为什么你对两个不同的东西使用相同的可变投资组合名称???
  • 你的 file_read 函数会以 dcitionary 的形式返回值吗??
  • 请分享你的整个代码???
  • gist.github.com/anonymous/790100c7d8d99f50be90 @Hackaholic 别介意第 64-68 行,现在只尝试不同的东西

标签: python list python-2.7 dictionary


【解决方案1】:

看起来file_read() 正在将文件读入字符串。

然后for line in portfolio: 将遍历该字符串中的每个字符

然后elements = line.strip().split(",") 会给你一个包含一个字符的列表,所以尝试获取elements[1] 超出了列表的范围。

如果要将文件的全部内容读入名为portfolio 的字符串中,可以使用

遍历字符串中的每一行
for line in porfolio.split('\n'):
    ...

但更常用的遍历文件行的方法是

with open(filename,'r') as inputfile:
    for line in inputfile:
         ....

【讨论】:

  • 如何让它不拆分成一个包含一个字符的列表?我希望它在逗号之前捕获所有内容。 @khelwood
  • 您的问题是for line in porfolioline 分配给一次一个字符。正如我在回答中所说的那样改变它。
  • 它适用于portfolio.split('\n') 中的for line。现在尝试在 for 循环之外使用文件时出现新错误,索引总是超出范围。 @khelwood
【解决方案2】:

让它与这个代码一起工作:

    for line in minfil :
    line = line.strip()
    elements = line.split(",")
    portfolio[str(elements[0])] = [(int(elements[1]),float(elements[2]), str(elements[3]))]   

【讨论】:

    猜你喜欢
    • 2022-12-21
    • 1970-01-01
    • 2021-09-09
    • 1970-01-01
    • 2020-06-02
    • 2014-03-14
    • 1970-01-01
    • 1970-01-01
    • 2019-11-08
    相关资源
    最近更新 更多