【问题标题】:i want to Make one list from list of list python with some condition i mentioned the expected output我想在某些条件下从列表 python 列表中创建一个列表,我提到了预期的输出
【发布时间】:2019-10-24 09:50:40
【问题描述】:

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

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

我想要这个输出

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

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

 for i in associated_values:
        s=''
        newlist.append(str(s.join(i)))

【问题讨论】:

标签: python


【解决方案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'"]
>>> 

我希望这是你想要的。

【讨论】:

  • 先生,这就是我想要的 ["chennai"," 'printer','pc' ,'notebook' "] 值应该在第二个列表中的 'quotes' 中
  • @mayankchauhan 有帮助吗?
【解决方案2】:

以下内容应该可以满足您的需求:

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

【讨论】:

    【解决方案3】:

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

    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'"]
    

    【讨论】:

      【解决方案4】:

      如果你想将输出作为一个列表,你可以使用这个:

      associated_values=[['chennai'], ['printer', 'pc', 'notebook']]
      
      newlist = []
      
      for i in associated_values:
          for _ in i:
              newlist.append(_)
      
      
      print(newlist)
      
      # Output : ['chennai', 'printer', 'pc', 'notebook']
      

      【讨论】:

        猜你喜欢
        • 2021-01-14
        • 1970-01-01
        • 1970-01-01
        • 2017-08-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-04
        相关资源
        最近更新 更多