关于Python 字典里的value
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了关于Python 字典里的value相关的知识,希望对你有一定的参考价值。
问题是有'a':[1,2,3,4],'b':[11,22,33], 即a中有4个值, b中有3个值
要弄成'a': [1,1,1,2,2,2,3,3,3,4,4,4], 'b':[11,11,11,11,22,22,22,22,33,33,33,33]
a和b中都要有3*4 = 12个值, 就是每个value的长度要一样
初学python,以此题练习,不求财富。
dic = 'a':[1,2,3,4], 'b':[11,22,33]
def gcd(m, n):
''' 求两个数的最大公约数 (greatest common divisor) '''
return m if n == 0 else gcd(n, m % n)
#三元表达式格式:true_part if condition else false_part
def lcm(m, n):
''' 求两个数的最小公倍数 (least common multiple) '''
return (m * n) / gcd(m, n)
lsLen = [len(dic['a']), len(dic['b'])]
lcmRet = lcm(lsLen[0], lsLen[1])
dicMultiple = 'a': lcmRet / lsLen[0], 'b': lcmRet / lsLen[1]
dicRet = 'a':[], 'b':[]
for key in dic:
for elem in dic[key]:
for n in range(dicMultiple[key]):
dicRet[key].append(elem)
print dicRet 参考技术A #先求最小公倍数,再整形
dic = 'sports' :'s.basketball':['a', 'b', 'c', 'd'], 's.football':['aa', 'bb', 'cc', 'dd'] ,
'music':'m.juzz':['e', 'f', 'g'], 'm.pop':['ee', 'ff', 'gg']
def gcd(a, b):
if b == 0:
return a
else:
return gcd(b, a % b)
def lcm(a, b):
return a * b / gcd(a, b)
myLcm = 1#最小公倍数
for k in dic:
for k2 in dic[k]:
myLcm = lcm(len(dic[k][k2]), myLcm)
newDiv =
for k in dic:
newDiv[k] =
for k2 in dic[k]:
newDiv[k][k2] = []
l = len(dic[k][k2])
for v in dic[k][k2]:
for i in range(myLcm / l):
newDiv[k][k2].append(v)
print newDiv追问
兄弟 你这个输出是字典里套字典, 我不用两个字典, 只要
'a': [1,1,1,2,2,2,3,3,3,4,4,4], 'b':[11,11,11,11,22,22,22,22,33,33,33,33]就行了, 能不能再麻烦帮我看看
以上是关于关于Python 字典里的value的主要内容,如果未能解决你的问题,请参考以下文章