私信  •  关注

Mauro Baraldi

Mauro Baraldi 最近创建的主题
Mauro Baraldi 最近回复了
6 年前
回复了 Mauro Baraldi 创建的主题 » 基于python中的条件创建一个列表以创建一个唯一的列表

添加标记时 算法 ,我相信你想要一个没有那么多魔法的解决方案。

>>> def merge_lists(A, B):
...     output = []
...     sub_list = []
...     current = A[0]
...     for i in range(len(A)):
...         if A[i] == current:
...             sub_list.append(B[i])
...         else:
...             output.append(sub_list)
...             sub_list = []
...             sub_list.append(B[i])
...             current = A[i]
...     output.append(sub_list)
...     return output
... 
>>> a= [0,0,0,1,1,1,3,3,3]
>>> b= ['a','b','c','d','e','f','g','h','i']
>>> merge_list(a, b)
[['a', 'b', 'c'], ['d', 'e', 'f'], ['g', 'h', 'i']]
6 年前
回复了 Mauro Baraldi 创建的主题 » 如何在Python中加载多个JSON对象

正如Daniel在评论中所说,重点关注JSON块的开始/结束模式。 }{ .

将所有数据加载到一个字符串中,将此模式替换为您可以处理的模式,并将其拆分为有效JSON数据的字符串列表。最后,遍历列表。

{ "a": 1,
"b" : 2,
"c" : {
        "d":3
        }
}{ "e" : 4,
"f" : 5,
"g" : {
        "h":6
        }
}

将数据加载到JSON有效字符串列表中

with open('/home/mauro/workspace/test.json') as fp:
    data = fp.read()

替换图案

data = data.replace('}{', '}\n\n{')

然后,将其拆分为JSON字符串valid列表

data = data.split('\n\n')

最后,遍历JSON字符串列表

for i in data:
    print json.loads(i)
6 年前
回复了 Mauro Baraldi 创建的主题 » 如何在python中根据字典键获取唯一的数据

遍历列表并将找到的每个第一个项添加到空列表中。

若要检查该值是否已找到,请将迭代中的当前项与查找列表进行比较。

uniq = []
found = []

for item in list_of_dictionaries:
    if item['series'] not in found:
        found.append(item['series'])
        uniq.append(item)

print(uniq)

关于这种方法的一些注意事项:

  • 它忽略了其他数据(键)。
  • 它正在获取列表的第一个匹配项。