获取列表的长度,其中包含多个列表(包含字典项)

时间:2018-03-08 05:29:01

标签: python

我有一个字典项列表的“列表”(强调引号),我试图得到它的长度。该项目的当前格式(类似JSON)如下所示:

x = {"fullgame":"+2","firsthalf":"Ev","secondhalf":"-1"}
{"fullgame":"-1.5","firsthalf":"Ev","secondhalf":""}
{"fullgame":"-2","firsthalf":"-0.5","secondhalf":""}
{"fullgame":"-1.5","firsthalf":"Ev","secondhalf":""}
{"fullgame":"-1.5","firsthalf":"-0.5","secondhalf":""}
{"fullgame":"-1.5","firsthalf":"Ev","secondhalf":""}

显然,如果格式正确,此列表的长度将为6。我一直试图在结束括号中分割项目或使用追加,但我总是得到每个项目长度的打印输出(或更糟)。基本上,我想我真的只是想把上面的对象变成下面打印的对象,因为我知道它得到了我正在寻找的输出......

x = [{"fullgame":"+2","firsthalf":"Ev","secondhalf":"-1"},
{"fullgame":"-1.5","firsthalf":"Ev","secondhalf":""},
{"fullgame":"-2","firsthalf":"-0.5","secondhalf":""},
{"fullgame":"-1.5","firsthalf":"Ev","secondhalf":""},
{"fullgame":"-1.5","firsthalf":"-0.5","secondhalf":""},
{"fullgame":"-1.5","firsthalf":"Ev","secondhalf":""},]

原谅新手问题。我一直在寻找这个问题的答案,但是我觉得这很简单。

编辑:我只是想让这个列表的长度远远超过6个条目。之后,我将遍历该列表,跳过每7个条目并提取特定值并将其推送到csv。虽然

,但我对该项目的这一部分没有任何问题

3 个答案:

答案 0 :(得分:0)

如果你的x是这样的,请尝试:

x = '{"fullgame":"+2","firsthalf":"Ev","secondhalf":"-1"}\
     {"fullgame":"-1.5","firsthalf":"Ev","secondhalf":""}\
     {"fullgame":"-2","firsthalf":"-0.5","secondhalf":""}\
     {"fullgame":"-1.5","firsthalf":"Ev","secondhalf":""}\
     {"fullgame":"-1.5","firsthalf":"-0.5","secondhalf":""}\
     {"fullgame":"-1.5","firsthalf":"Ev","secondhalf":""}'

import ast
import re

text = re.sub(r'(})', r'\1,', x)
result = ast.literal_eval(text)
print(list(result))

它会像:

[{'secondhalf': '-1', 'fullgame': '+2', 'firsthalf': 'Ev'}, 
 {'secondhalf': '', 'fullgame': '-1.5', 'firsthalf': 'Ev'}, 
 {'secondhalf': '', 'fullgame': '-2', 'firsthalf': '-0.5'}, 
 {'secondhalf': '', 'fullgame': '-1.5', 'firsthalf': 'Ev'}, 
 {'secondhalf': '', 'fullgame': '-1.5', 'firsthalf': '-0.5'},    
 {'secondhalf': '', 'fullgame': '-1.5', 'firsthalf': 'Ev'}]

然后您可以轻松找到列表的长度,例如print(len(list(result)))

答案 1 :(得分:0)

假设你有'x'作为字符串,你可以这样做:

x = x.replace("}{","}!!@${")
l = x.split("!!@$") # Add some dummy delimiter
print(len(l))
print(l[0])
  

6

     

{ “fullgame”: “+ 2”, “firsthalf”: “EV”, “secondhalf”: “ - 1”}

答案 2 :(得分:0)

如果你只想要字符串中每个字典的计数......

x = """{"fullgame":"+2","firsthalf":"Ev","secondhalf":"-1"}
{"fullgame":"-1.5","firsthalf":"Ev","secondhalf":""}
{"fullgame":"-2","firsthalf":"-0.5","secondhalf":""}
{"fullgame":"-1.5","firsthalf":"Ev","secondhalf":""}
{"fullgame":"-1.5","firsthalf":"-0.5","secondhalf":""}
{"fullgame":"-1.5","firsthalf":"Ev","secondhalf":""}"""

print(x.count("}\n{")+1)

<强>输出:

6