python - 有没有更好的方法来合并具有子列表的元组的项目,而无需创建如下所示的新函数?
问题描述
我有一个清单:
k_list = [(1,2,3,['a','b','c']), (4,5,6,['d','e','f']), (7,8,9,['g','h','i'])]
想要合并每个元组的子列表,例如:
[(1, 2, 3, 'a', 'b', 'c'), (4, 5, 6, 'd', 'e', 'f'), (7, 8, 9, 'g', 'h', 'i')]
或者
[[1, 2, 3, 'a', 'b', 'c'], [4, 5, 6, 'd', 'e', 'f'], [7, 8, 9, 'g', 'h', 'i']]
我想出了以下解决方案:
new_list =[]
def removeNesting(nest):
for e in nest:
if type(e) == list:
removeNesting(e)
else:
output.append(e)
return output
for i in k_list:
output = []
new_list.append(removeNesting(i))
print new_list
但我不觉得它是一个理想的解决方案,所以尝试在不使用函数的情况下做某事,当列表中没有整数时,下面的代码可以正常工作:
new_list1 = []
for e in k_list:
total = []
for i in e:
total += i
new_list1.append(total)
print new_list1
但是当列表中有整数时,我在这一行得到错误: total += i
TypeError:“int”对象不可迭代
如何解决这个问题?
感谢您的阅读和提前帮助!!
解决方案
只需列表理解:
>>> [(a,b,c,*d) for a,b,c,d in k_list]
[(1, 2, 3, 'a', 'b', 'c'), (4, 5, 6, 'd', 'e', 'f'), (7, 8, 9, 'g', 'h', 'i')]
推荐阅读
- json - 放心的两个不同json文件之间的依赖关系
- node.js - 如何将 cookie 从外部附加到 cookieJar、nodeJS
- python - 带枚举的有序字典python
- azure - 在 azure 函数中共享 Cloud* 对象
- google-bigquery - 从扁平结构创建具有多个嵌套级别的表
- c# - 一对一变成一对多 Entity Framework 生成数据库优先
- ios - BW Facebook Login 和 FBSDKLoginKit Pod 的区别以及使用哪一个?
- c# - 无法加载文件或程序集“Twilio,版本=5.9.7.0,Culture=neutral,PublicKeyToken=null”。该系统找不到指定的文件。'
- nginx - nginx 数字子域返回冲突的服务器名称
- javascript - 如何在 Vue 中只激活手风琴的一项?