我想在某些条件下从列表python列表中创建一个列表,我提到了预期的输出

时间:2019-10-24 09:50:40

标签: python

我有一个列表列表,我想将它们与合并为一个

DiffUtil

我想要这个输出

associated_values=[['chennai'], ['printer', 'pc', 'notebook']]

此代码不起作用。我希望将两个列表作为两个逗号分隔的字符串值与所需的输出相同。

["chennai","'printer','pc','notebook'"]

4 个答案:

答案 0 :(得分:1)

这有效:

associated_values=[['chennai'], ['printer', 'pc', 'notebook']]
newlist = []
for i in associated_values:
    if len(i) == 1:
        newlist.append("'"+str(i[0]+"'"))
    else:
        s = ''
        for item in i:
            if item != i[0]:
                s += ' ,' + "'"+str(item)+ "'"
            else:
                s += "'"+str(item)+"'"
        newlist.append(s)
print(newlist)

输出

============================== RESTART: D:\x.py ==============================
["'chennai'", "'printer' ,'pc' ,'notebook'"]
>>> 

我希望这就是你想要的。

答案 1 :(得分:-1)

以下内容应为您提供所需的内容:

for e in associated_values:
    newlist.append(str(e)[1:-1])

答案 2 :(得分:-1)

您可以使用以下方法解决您的问题:

associated_values=[['chennai'], ['printer', 'pc', 'notebook']]
result = list(map(lambda x: ','.join(map(lambda y: "'" + y + "'" if len(x) > 1 else y, x)), associated_values))
print(result)
# ['chennai', "'printer','pc','notebook'"]

答案 3 :(得分:-2)

如果要以列表形式输出,则可以使用:

associated_values=[['chennai'], ['printer', 'pc', 'notebook']]

newlist = []

for i in associated_values:
    for _ in i:
        newlist.append(_)


print(newlist)

# Output : ['chennai', 'printer', 'pc', 'notebook']