我正在尝试解决一个练习,我必须转换这个
L = ([[4,1],[2,2],[2,"test"],[3,3],[1,"bonjour"]])
decompress (L)
进入这个
[1,1,1,1,2,2,"test","test",3,3,3,"bonjour"]
这就是我开始的方式:
def por(L):
result = []
n = len(L)
for i in range(n):
m = len(L[i])
for j in range(m):
mult = L[j]*L[j-1]
result.append(mult)
return result
por([[4,1],[2,2],[2,"test"],[3,3],[1,"bonjour"]])
Traceback (most recent call last):
File "<pyshell#50>", line 1, in <module>
por([[4,1],[2,2],[2,"test"],[3,3],[1,"bonjour"]])
File "<pyshell#49>", line 7, in por
mult = L[j]*L[j-1]
TypeError: can't multiply sequence by non-int of type 'list'
我没有弄错,有人可以帮助我,这是我的考试!!!!
答案 0 :(得分:1)
def por(L):
# add each sublist element 1 sublist element 0 times
return [sub_list[1] for sub in L for _ in xrange(sub_list[0])]
或者:
def por(L):
return [ele for times, ele in L for _ in xrange(times)]
使用与您自己的代码类似的东西:
def por(L):
result = []
# loop over each sublist
for sub_list in L:
# get first sublist element and loop in that range
times = sub_list[0] # actually accessing the first element of each sublist
for _ in xrange(times): # use range for python 3
# here we are adding each sublist element 1 element 0 times
result.append(sub_list[1])
return result
在您的代码中,您尝试将L[j]* L[j-1]
乘以两个列表,就像您在代码中添加print L[j],L[j-1]
时所看到的那样:
[4, 1] [1, 'bonjour']
[2, 2] [4, 1]
[4, 1] [1, 'bonjour']
[2, 2] [4, 1]
[4, 1] [1, 'bonjour']
[2, 2] [4, 1]
[4, 1] [1, 'bonjour']
[2, 2] [4, 1]
[4, 1] [1, 'bonjour']
[2, 2] [4, 1]
答案 1 :(得分:1)
也许最简单:
result = []
for repetitions, contents in L:
for _ in range(repetitions):
result.append(contents)
是的,有更好的方法,其中一些已经发布,但也许这个的简单性会有所帮助。
避免len
调用和索引,有利于循环遍历列表并将其每个项目解压缩到repetitions
和content
,我觉得有助于简单化;所以从一个重复的append
调用的空列表中构建结果,而不是更加惯用但可能更模糊,更初学者使用列表推导和&amp; c。
答案 2 :(得分:0)
我个人觉得itertools可以让我们的生活更容易解决这些问题:
def por(L):
chains = (itertools.repeat(b, a) for a, b in L)
return list(itertools.chain_from_iterable(chains))
或者,一行:
>>> list(itertools.chain_from_iterable(itertools.repeat(b, a) for a, b in L))
[1, 1, 1, 1, 2, 2, 'test', 'test', 3, 3, 3, 'bonjour']
答案 3 :(得分:0)
>>> L = ([[4,1],[2,2],[2,"test"],[3,3],[1,"bonjour"]])
>>> [y for x, y in L for i in range(x)]
[1, 1, 1, 1, 2, 2, 'test', 'test', 3, 3, 3, 'bonjour']