[英]python merging list within lists
im pretty nooby at python. 我在python上很漂亮 However, i am trying to merge a list of data lists or a list with a element thats inside a list.
但是,我试图合并一个数据列表列表或一个列表里面的元素列表。 Anyways, in essence it looks like this...
无论如何,本质上看起来像这样...
example: 例:
data_list = ["x, cat, x, 8, ["10"]"] data_list = [“ x,cat,x,8,[” 10“]”]
and i want it to look like this... 我希望它看起来像这样...
data_list = ["x, cat, x, 8, 10"] data_list = [“ x,cat,x,8,10”]
i have tried to make a new list and .append() it to that but the result does not seem any different. 我试图制作一个新列表并对其进行.append(),但结果似乎没有任何不同。 itertools breaks up every item into a string separated by a comma.
itertools将每个项目分解为一个用逗号分隔的字符串。
using reduce(lambda x,y: x+y,data_list) only removes the outer brackets so it looks like this when printed to the shell: 使用reduce(lambda x,y:x + y,data_list)仅除去外括号,因此在打印到外壳时看起来像这样:
data_list = x, cat, x, 8, ["10"] data_list = x,cat,x,8,[“ 10”]
is there a way that i can remove the inner brackets using lambda ? 有没有办法我可以使用lambda卸下内支架? or any method that give me the same outcome?
或任何可以给我相同结果的方法?
It looks like you are trying to flatten a list with some elements which are lists and some which are not. 看起来您正在尝试使用一些元素(这些元素是列表元素,有些不是)来展平列表。 The following does what you want, assuming that your nested lists have only one element.
假设您的嵌套列表只有一个元素,下面的操作就可以满足您的要求。
data_list = ["x", "cat", "x", 8, ["10"]]
def Strip(x):
if isinstance(x, list):
return x[0]
return x
newlist = [Strip(x) for x in data_list]
print newlist
Here's another, perhaps more readable solution that will handle nested lists with multiple elements, but not multiple layers of nesting. 这是另一个可能更具可读性的解决方案,该解决方案将处理具有多个元素而不是多层嵌套的嵌套列表。
data_list = ["x", "cat", "x", 8, ["10",10]]
new_list = []
for x in data_list:
if isinstance(x,list):
new_list += x
else:
new_list.append(x)
print new_list
If we assume that data_list
starts out as as list containing a single string
rather than a list
object, we can convert it into a list first before using the methods above. 如果我们假设
data_list
以包含单个string
而不是list
对象的list
,则可以在使用上述方法之前先将其转换为列表。
import ast
data_list = ast.literal_eval(data_list[0])
and convert it back after we are done: 并在完成后将其转换回:
new_list = [new_list.__str__()]
Using replace, join and map: 使用替换,联接和映射:
print ["".join(map(lambda x: x.replace('[','').replace(']','').replace('"',''), ''.join(data_list).split()))]
output: 输出:
["x,cat,x,8,10"]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.