【问题标题】:File, strip each line and add to key in dictionary文件,剥离每一行并添加到字典中的键
【发布时间】:2013-12-17 00:34:26
【问题描述】:

我们如何拆分文本文件中的第一行并将它们作为键,以及 之后的每一行都是每个键的值。 没有任何进口

到目前为止我所拥有的:

new_dict = {}
with open(file, 'r') as f:
    for line in f:
        list = line.strip().split(',')
        for item in list:
            new_dict[item] = []

这会输出什么:{'name': [], 'last': [], 'middle': []}

现在,我如何移动到下一行,以逗号分隔并将第一个元素附加到第一个键,将第二个元素附加到第二个键,等等。

file:
name, last, middle
bob, jones, m
jones, bob, k
alice, lol, f

最终结果:

{'name': ['bob', 'jones', 'alice'], 'last': ['jones', 'bob', 'lol'], 'middle': ['m', 'k', 'f']}

【问题讨论】:

  • 他们确实说“没有任何进口”。
  • 为什么“没有任何进口”?我以为在 python 中你只是“导入解决方案”

标签: python file dictionary


【解决方案1】:
new_dict = {}
names = [] # used map 0, 1, 2 to `name`, `last`, `middle`
with open('/path/to/test.txt') as f:

    # Handle header (the first) line: `name, last, middle`
    for name in next(f).split(','): # split fields by `,`
        name = name.strip()  # remove surrounding spaces
        names.append(name)
        new_dict[name] = []  # initialize dictionary with empty list.

    # Handle body.
    for line in f:
        # enumerate(['bob', 'jones', 'm']) return an interator
        #    that generates (0, 'bob'), (1, 'jones'), (2, 'm')
        for i, value in enumerate(line.split(',')):
            new_dict[names[i]].append(value.strip())

print(new_dict)

输出:

{'middle': ['m', 'k', 'f'], 'last': ['jones', 'bob', 'lol'], 'name': ['bob', 'jones', 'alice']}

【讨论】:

  • 谢谢你,但你能给我解释一下这部分:for name in next(f).split(','): name = name.strip() names.append(name) new_dict[名称] = []
  • @Sc4r,我在代码中添加了 cmets。如果不清楚,请告诉我。
  • next(f) 是做什么的?是第一行之后的下一行吗?
  • @Sc4r, next(f) 返回一行;用于获取第一行。就像f.readline()
  • 哦,好吧,现在说得通了,我不确定接下来要做什么。您能否也解释一下枚举部分?
【解决方案2】:
answer = {}
for attr in "name last middle".split():
  answer[attr] = []
with open("path/to/input") as infile:
  for line in infile:
    for k,v in zip("name last middle".split(), line.strip().split(',')):
      answer[k].append(v)

【讨论】:

    【解决方案3】:

    我猜逻辑是:

    1. 阅读第一行,将其拆分为,
    2. 获取每个值并创建字典的键。
    3. 阅读其余行并将它们添加到与正确“列”或键对应的列表中。

    这是上述逻辑的一种方法:

    d = {}
    with open('somefile.txt') as f:
       first_line = next(f)
       for column_title in first_line.split(','):
           d[column_title.strip()] = []
       for line in f:
           if line.strip():
               # this will skip blanks
               name, last, middle = line.split(',')
               d['name'].append(name.strip())
               d['last'].append(last.strip())
               d['middle'].append(middle.strip())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-05
      • 2021-11-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多