python - 满足条件时重置列表

标签 python list dictionary

我正在尝试创建一个函数,该函数读取 Protocol Buffer 并创建一个字典,其中的列表与每个键匹配,如下所示:

Source:
  {
    name: "foo"
    ...
    some_value: "a"
    some_value: "b"
  },
  {
    name: "bar"
    ...
    some_value: "c"
    some_value: "d"
  }

Desired Output:
  {'foo': ['a','b'], 'bar': ['c','d',]}

这是我的代码:

import re

STATIC_SRC = '/path/to/my/file.txt'

def CountBrackets(line):
  if '{' in line:
    return 1
  if '}' in line:
    return -1
  else:
    return 0

with open(STATIC_SRC, 'r') as src_file:
  bracket_count = 0
  key = ''
  values = []
  my_dict = {}

  for line in src_file:
    line = line.strip()
    bracket_count += CountBrackets(line)

    # Finds line like 'name: "foo"' and stores 'foo' as key
    if line.startswith('name:'):
      key = re.findall('"([^"]*)"', line)
      key = ''.join(key)

    # Finds line like 'some_value: "a"' and adds 'a' to list
    if line.startswith('some_value:'):
      value = re.findall('"([^"]*)"', line)
      values.append(value)

    # When bracket count returns to 0, it's reached the end of a tupe
    # and should store the current key and list.
    if bracket_count == 0:
      my_dict[key] = values
      del values[:] # This is where I'm having issues.

  print(role_dict)

我的问题是我无法在元组末尾(在源文件中)成功清除列表。我尝试了以下两种方法,都没有给出正确的输出。

Method:
  values = []
Result:
  {'foo': ['a', 'b'], 'bar': ['a','b','c','d']}

Method:
  del values[:]
Result:
  {'foo': [], 'bar': []}

我已经让它在循环时打印所有键/值,并且它们按预期工作。它还根据括号计数在写入时写入字典。看来我用于清除的方法以某种方式清除了“值”,即使它们已添加到字典中也是如此。

任何人都可以阐明这里出了什么问题以及如何正确清空值列表吗?谢谢!

编辑:根据要求,tl;dr

我希望程序循环执行此逻辑:

if x:
  - store something to 'key'
if y:
  - add something to a list 'values'
if z:
  - write the current 'key' and 'values' to a dictionary
  - clear the list 'values'

如何清除末尾的值列表?

最佳答案

我不知道为什么您在第一次尝试时会得到该输出。这对我有用。见下文。

with open(STATIC_SRC, 'r') as src_file:
  bracket_count = 0
  key = ''
  values = []
  my_dict = {}

  for line in src_file:
    print(values)
    line = line.strip()
    bracket_count += CountBrackets(line)

    # Finds line like 'name: "foo"' and stores 'foo' as key
    if line.startswith('name:'):
      key = re.findall('"([^"]*)"', line)
      key = ''.join(key)

    # Finds line like 'some_value: "a"' and adds 'a' to list
    if line.startswith('some_value:'):
      value = re.findall('"([^"]*)"', line)
      values.extend(value)  # append create a new list inside the existing list

    # When bracket count returns to 0, it's reached the end of a tupe
    # and should store the current key and list.
    if bracket_count == 0:
      my_dict[key] = values
      values = []

  print(my_dict)  # the name of the dict was wrong

结果是

{'foo': ['a', 'b'], 'bar': ['c', 'd']}

我刚刚编辑了最后一个打印并将追加替换为扩展。

您不能删除值,因为这会删除字典中的值,因为它是内存中的同一个对象。

d = {}
k = [1,2,3]
d['a'] = k
d
#  {'a': [1, 2, 3]}
id(d['a']) == id(k)
#  True

运行Python 2.7.6。

关于python - 满足条件时重置列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34214029/

相关文章:

python - flask - ImportError : No module named app

python - 如何将数据从python快速发送到hadoop

c# - 什么是更好、更干净的使用 List<T> 的方法

Java 使用 Stream 对列表进行排序和分组

c# - 从抽象类型对象数组访问特定子类的对象

java - 在 Java 中将 List<> 内容过滤到字典中

python - Selenium 错误消息 "selenium.webdriver has no attribute execute script"

python - ModuleNotFoundError : No module named 'pymysql' in jupyter

C++ map 定义基础

java - map 上复杂操作的问题