map.join 函数错误:返回字母列表

我有两个列表列表,但是,当实现映射/连接函数时,它们返回了不同的结果。第一个是我想要的结果。


list1 = ['I woke up at 6am today.',

     'I live in vancouver.',

     'I go to gym by 6pm.',]


list2 =`[['7am run 🏃\u200d♂️ done ✅ @kristianevofit @ottowallin @trboxing @btsport @ringtv @frank_warren_official @mtkglobal @marbella.co.uk'],

['我已经屈服于#bottlecapchallenge 😂⛑🙈 你怎么看?#bluesteel #scrubs']]`


功能:


[''.join(x) for x in list1]

[''.join(x) for x in list2]


list1 的结果:


['I woke up at 6am today.',

 'I live in vancouver.',

 'I go to gym by 6pm.',]

结果list2:


['[',

 '[',

 "'",

 '7',


 'a',

 'm',

 ' ',

 'r',

 'u',]']

期望的结果是在 on 上产生与 on 相同的list2结果list1。


手掌心
浏览 89回答 2
2回答

喵喵时光机

你list2是一个列表列表,string而你list1是一个字符串列表。因此,您需要展平您list2的以获得list1如下结果。import ast# Convert to listlist2 = ast.literal_eval(list2)# Flatten nested list/list of list into listflat_list2 = [y for x in list2 for y in x]# Then you can use thisresult = [''.join(x) for x in List2]或者,您可以将它们组合起来:import astlist2 = ast.literal_eval(list2)result [''.join(y) for x in list2 for y in x]当然,您需要确保您的嵌套列表字符串必须遵循正确的 Python 语法。下面是运行的代码IPythonIn [1]: list2 = """[[\'7am run 🏃\\u200d♂️ done ✅ @kristianevofit @ottowallin @trboxing @btsport @ringtv @frank_warren_official @mtkglobal @marbella.co.uk\'],      ...: [\'I have succummed to the #bottlecapchallenge 😂⛑🙈 What do you think? #bluesteel #scrubs\']]"""                                                                                                          In [2]: import ast                                                                                                                                                                                                 In [3]: list2 = ast.literal_eval(list2)                                                                                                                                                                            In [4]: result = [''.join(y) for x in list2 for y in x]                                                                                                                                                            In [5]: result                                                                                                                                                                                                     Out[5]: ['7am run 🏃\u200d♂️ done ✅ @kristianevofit @ottowallin @trboxing @btsport @ringtv @frank_warren_official @mtkglobal @marbella.co.uk', 'I have succummed to the #bottlecapchallenge 😂⛑🙈 What do you think? #bluesteel #scrubs']

慕田峪9158850

您可以使用ast.literal_eval这对您很有用:import ast list2 = ast.literal_eval(list2)result2 = [''.join(x) for x in List2]
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python