如何将子列表添加到子列表?
How to add a sublist to a sublist?
我想在某些情况下将子列表附加到前一个子列表,即如果它的长度小于 2。因此,[5]
的长度小于 2,现在要扩展前一个列表与 5 (a+b)。
a = [1,1,1,1]
b = [5]
c = [1,1,1]
d = [1,1,1,1,1]
e = [1,2]
f = [1,1,1,1,1,1]
L = [a,b,c,d,e,f]
print 'List:', L
def short(lists):
result = []
for value in lists:
if len(value) <= 2 and result:
result[-1] = result[-1] + value
return result
result = short(L)
print 'Result:', result
结果应该是:[[1, 1, 1, 1, 5], [1, 1, 1], [1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 1, 1]]
但是从我的代码中,我得到:[]
这可能有帮助
例如:
a = [1,1,1,1]
b = [5]
c = [1,1,1]
d = [1,1,1,1,1]
e = [1,2]
f = [1,1,1,1,1,1]
L = [a,b,c,d,e,f]
print( 'List:', L)
def short(lists):
result = []
for value in lists:
if len(value) <= 2: #check len
result[-1].extend(value) #extend to previous list
else:
result.append(value) #append list.
return result
result = short(L)
print( 'Result:', result)
输出:
List: [[1, 1, 1, 1], [5], [1, 1, 1], [1, 1, 1, 1, 1], [1, 2], [1, 1, 1, 1, 1, 1]]
Result: [[1, 1, 1, 1, 5], [1, 1, 1], [1, 1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 1, 1]]
将您的函数更改为:
def short(lists):
result = []
for value in lists:
if len(value) < 2 and result:
result[-1].extend(value)
else:
result.append(value)
return result
我想在某些情况下将子列表附加到前一个子列表,即如果它的长度小于 2。因此,[5]
的长度小于 2,现在要扩展前一个列表与 5 (a+b)。
a = [1,1,1,1]
b = [5]
c = [1,1,1]
d = [1,1,1,1,1]
e = [1,2]
f = [1,1,1,1,1,1]
L = [a,b,c,d,e,f]
print 'List:', L
def short(lists):
result = []
for value in lists:
if len(value) <= 2 and result:
result[-1] = result[-1] + value
return result
result = short(L)
print 'Result:', result
结果应该是:[[1, 1, 1, 1, 5], [1, 1, 1], [1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 1, 1]]
但是从我的代码中,我得到:[]
这可能有帮助
例如:
a = [1,1,1,1]
b = [5]
c = [1,1,1]
d = [1,1,1,1,1]
e = [1,2]
f = [1,1,1,1,1,1]
L = [a,b,c,d,e,f]
print( 'List:', L)
def short(lists):
result = []
for value in lists:
if len(value) <= 2: #check len
result[-1].extend(value) #extend to previous list
else:
result.append(value) #append list.
return result
result = short(L)
print( 'Result:', result)
输出:
List: [[1, 1, 1, 1], [5], [1, 1, 1], [1, 1, 1, 1, 1], [1, 2], [1, 1, 1, 1, 1, 1]]
Result: [[1, 1, 1, 1, 5], [1, 1, 1], [1, 1, 1, 1, 1, 1, 2], [1, 1, 1, 1, 1, 1]]
将您的函数更改为:
def short(lists):
result = []
for value in lists:
if len(value) < 2 and result:
result[-1].extend(value)
else:
result.append(value)
return result