[英]Combining elements in list using python
Given input:给定输入:
list = [['a']['a', 'c']['d']]
Expected Ouput:预期输出:
mylist = a,c,d
Tried various possible ways, but the error recieved is TypeError: list indices must be integers not tuple.尝试了各种可能的方法,但收到的错误是 TypeError: list indices must be integers not tuple。
Tried: 1.试过:1。
k= []
list = [['a']['a', 'c']['d']]
#k=str(list)
for item in list:
k+=item
print k
2. 2.
print zip(*list)
etc.等等
Also to strip the opening and closing parenthesis.还要去掉左括号和右括号。
What you want is flattening a list .你想要的是扁平化一个列表。
>>> import itertools
>>> l
[['a'], ['a', 'c'], ['d']]
>>> res = list(itertools.chain.from_iterable(l))
>>> res
['a', 'a', 'c', 'd']
>>> set(res) #for uniqify, but doesn't preserve order
{'a', 'c', 'd'}
Edit: And your problem is, when defining a list, you should seperate values with a comma.编辑:你的问题是,在定义一个列表时,你应该用逗号分隔值。 So, not:
所以,不是:
list = [['a']['a', 'c']['d']]
Use commas:使用逗号:
list = [['a'], ['a', 'c'], ['d']]
And also, using list
as a variable is a bad idea, it conflicts with builtin list
type.而且,使用
list
作为变量是一个坏主意,它与内置list
类型冲突。
And, if you want to use a for loop:而且,如果您想使用 for 循环:
l = [['a'], ['a', 'c'], ['d']]
k = []
for sublist in l:
for item in sublist:
if item not in k: #if you want list to be unique.
k.append(item)
But using itertools.chain is better idea and more pythonic I think.但是我认为使用 itertools.chain 是更好的主意,而且更 Pythonic。
While utdemir's answer does the job efficiently, I think you should read this - start from "11.6. Recursion".虽然 utdemir 的回答有效地完成了这项工作,但我认为您应该阅读这篇文章 - 从“11.6. Recursion”开始。 The first examples deals with a similar problem, so you'll see how to deal with these kinds of problems using the basic tools.
第一个示例处理类似的问题,因此您将了解如何使用基本工具处理这些类型的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.