从列表获取键和值
我有问题与制作字典,并从我的名单和值列表中获取键和值。从列表获取键和值
名单如下:
['smer', '1245', 'kdh', '7845', 'smer', '697', 'sns', '78', 'du', '421', 'smer', '632', 'ol', '4144', 'most-hid', '457', 'smer', '12', 'ol', '897', 'most-hid', '1234', 'kdh', '555', 'ol', '898', 'du', '7845']
我的问题是我如何获得的名称为键和数字作为值。
如果密钥已经在字典中,它会将这些值相加在一起。
然后我怎么从它做一个饼图。
我刚刚学习python,我无法弄清楚这一点。
def strany():
slovnik={}
zoznam=[]
x=open('Strany.txt','r')
for i in x.readlines():
i=i.strip()
casty=i.split(' ')
for x in casty:
zoznam.append(x)
我不如何继续
谢谢您的建议。
可以使用collections.defaultdict重复键求和值,致电名单上ite
r和荏苒后解压缩在一个循环中每个配对:
l = ['smer', '1245', 'kdh', '7845', 'smer', '697', 'sns', '78', 'du', '421', 'smer', '632', 'ol', '4144', 'most-hid', '457', 'smer', '12', 'ol', '897', 'most-hid', '1234', 'kdh', '555', 'ol', '898', 'du', '7845']
from collections import defaultdict
d = defaultdict(int)
it = iter(l)
for k,v in zip(it,it):
d[k] += int(v)
print(d)
defaultdict(<class 'int'>, {'sns': 78, 'ol': 5939, 'du': 8266, 'smer': 2586, 'most-hid': 1691, 'kdh': 8400})
如果配对是从未来文件只要解,当您去使用CSV LIB来解析该文件假设你的数据是由whitesapce分隔:
from collections import defaultdict
import csv
with open("infile") as f:
d = defaultdict(int)
for k,v in csv.reader(f,delimiter=" "):
d[k] += int(v)
print(d)
你可以达到同样的使用普通的字典和dict.setdefault
:
with open("infile") as f:
d = {}
for k,v in csv.reader(f,delimiter=" "):
d.setdefault(k , 0)
d[k] += int(v)
只需遍历列表,逐步加2,并抓住每个键/值。像这样
l = ['1','a','2','b','3','c']
for i in range(0, len(l), 2):
print('key=' + l[i] + 'value=' + l[i+1])
替换为任何适合您的问题
import matplotlib.pyplot as plt
summed = {}
x = ['smer', '1245', 'kdh', '7845', 'smer', '697', 'sns', '78', 'du', '421', 'smer', '632', 'ol', '4144', 'most-hid', '457', 'smer', '12', 'ol', '897', 'most-hid', '1234', 'kdh', '555', 'ol', '898', 'du', '7845']
it = iter(x)
for k,v in zip(it,it):
summed[k] = summed.get(k,0) + float(v)
plt.pie(summed.values(), labels=summed.keys())
plt.show()
而且处理文件的一部分,假设你想在文件中所有行一个饼图的打印功能:
import matplotlib.pyplot as plt
with open('Strany.txt') as f:
it = (y for z in f for y in z.strip().split())
summed = {}
for k,v in zip(it,it):
summed[k] = summed.get(k,0) + float(v)
plt.pie(summed.values(), labels=summed.keys())
plt.show()
先阅读问题。 –
谢谢@AhsanulHaque – fivetentaylor
statistics.sk正在为选举做准备? muhehehe
result = {}
a=['smer', '8', 'kdh', '7', 'smer', '6']
while a:
party = a.pop(0)
number = int(a.pop(0))
if (party in result.keys()):
result[party]+=number
else:
result[party]=number
不幸的是,但它是奖金作业的任务,所以我试图做,但现在我赶时间 –
@Padraic坎宁安你100%正确。你的回答是真正的python矿是'python for dummies'(没有冒犯)。 – poko
我不想冒犯,但这不应该是赢家。在 – fivetentaylor
您可以从列表中进行迭代器并使用它的next
方法
lt_iter= iter(lst)
dic={}
while True:
try:
key=lt_iter.next()
value= lt_iter.next()
if key in dic:
dic[key]+=value
else:
dic[key]=value
except StopIteration:
break
print dic
加载到一个字典是容易的,但你需要像一个绘图库Matplotlib来生成饼图。
#load the value in the list
k = ['smer', '1245', 'kdh', '7845', 'smer', '697', 'sns', '78', 'du', '421', 'smer', '632', 'ol', '4144', 'most-hid', '457', 'smer', '12', 'ol', '897', 'most-hid', '1234', 'kdh', '555', 'ol', '898', 'du', '7845']
#create a dictionary to hold the values
d = {}
for i in range(0,len(k),2):#iterate the length of the list, i will be every other index
key = k[i]
val = float(k[i+1])
if d.has_key(key): #if the key exists perform summation
d[key] += val
else: #if the key does not exist create it
d[key] = val
# a plotting library like matplot lib is required for the pie chart
import matplotlib.pyplot as plt
labels = d.keys()
values = d.values()
plt.pie(values, # data
labels=labels, # slice labels
autopct='%1.1f%%', # print the values inside the wedges
)
plt.show()
你有什么试过的?什么具体不工作?你得到什么错误?你的代码是什么样的? – DilithiumMatrix
首先不要建立列表。直接从文件构建字典要容易得多。当你建立这个列表时,你会失去文件给你的自然分组。 – user2357112
@ user2357112,这对于重复键不起作用 –