为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

手掌心 2022-05-24 09:36:46
我有两个列表列表,但是,当实现映射/连接函数时,它们返回了不同的结果。第一个是我想要的结果。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。
查看完整描述

2 回答

?
喵喵时光机

TA贡献1846条经验 获得超7个赞

你list2是一个列表列表,string而你list1是一个字符串列表。因此,您需要展平您list2的以获得list1如下结果。


import ast


# Convert to list

list2 = ast.literal_eval(list2)


# Flatten nested list/list of list into list

flat_list2 = [y for x in list2 for y in x]


# Then you can use this

result = [''.join(x) for x in List2]

或者,您可以将它们组合起来:


import ast


list2 = ast.literal_eval(list2)

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

当然,您需要确保您的嵌套列表字符串必须遵循正确的 Python 语法。下面是运行的代码IPython


In [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']



查看完整回答
反对 回复 2022-05-24
?
慕田峪9158850

TA贡献1794条经验 获得超7个赞

您可以使用ast.literal_eval这对您很有用:


import ast 

list2 = ast.literal_eval(list2)

result2 = [''.join(x) for x in List2]


查看完整回答
反对 回复 2022-05-24
  • 2 回答
  • 0 关注
  • 85 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信