【问题标题】:How to create nested list using special condition in python如何在python中使用特殊条件创建嵌套列表
【发布时间】:2015-05-23 17:35:37
【问题描述】:

我真的很感谢我的问题的答案。
所以问题:我有一个列表

Plist=[[x1,y2,str_1],[x2,y2,str_1],[x3,y3,str_1],[x4,y4,str_2],[x5,y5,str_2]]  

并希望将其转换为嵌套列表(现在将避免使用 dict):

newPlist=[[[x1,y2,str_1],[x2,y2,str_1],[x3,y3,str_1]],[[x4,y4,str_2],[x5,y5,str_2]]]  

我知道如何根据长度对其进行排序,但如果我有特殊情况(在我的情况下为Plist[][2]),我无法确定它
到目前为止我已经尝试过: 分组数据:

for elt, items in groupby(Plist, itemgetter(2)):

print elt, item  
    for i in items:  
        print i    

然后我就卡住了之后要写什么

 newPlist=[]  
 newPlist.append(???)  

看了论坛,我觉得这是基本的东西,但我就是想不通。我找到了 panda 和 numpy,但由于特殊原因,我无法使用它们。 提前非常感谢您!!!

【问题讨论】:

    标签: python list nested conditional-statements


    【解决方案1】:

    您可以在每个items 上应用list

    newPlist.append(list(items))
    

    例如,第一个 list(items) 将评估为:

    [['x1', 'y2', 'str_1'], ['x2', 'y2', 'str_1'], ['x3', 'y3', 'str_1']]
    

    等等。

    请注意,由于每个items 都是一个生成器,因此您需要删除打印循环以避免消耗生成器的内容,否则list(items) 将只是一个空列表。

    【讨论】:

    • 谢谢,它几乎可以做到,我想要的,但它以某种方式削减了第一项。
    • 所以实际上我得到了这个:[[['x2', 'y2', 'str_1'], ['x3', 'y3', 'str_1']], [['x5 ', 'y5', 'str_2']]]
    • 对不起,它就像魅力一样!忘记删除第二个循环。
    猜你喜欢
    • 2021-08-15
    • 2011-01-11
    • 2022-01-16
    • 1970-01-01
    • 1970-01-01
    • 2022-12-03
    • 2017-10-01
    • 1970-01-01
    相关资源
    最近更新 更多