简体   繁体   English

将项目添加到列表中的特定位置

[英]Adding items to specific places in list

x=len(sorted_list)
z=1
for y in range (2,x):
    if sorted_list[y][1]=="0" and len(sorted_list[y])>3:
        z+=1
        sorted_list.insert(y,'Message '+ str(z))
        x+=1
    else:
        continue

I have a list named "sorted_list".我有一个名为“sorted_list”的列表。 I want to add some items to list but i have a problem.我想在列表中添加一些项目,但我遇到了问题。 When i try this code it goes to infinity.当我尝试这段代码时,它会变得无穷大。 I want to group numbers by 0th index.我想按第 0 个索引对数字进行分组。 I have an input like that:我有这样的输入:

[['65', '0', 'Hello'],
['65', '1', 'world'],
['78', '0', "what's"],
['78', '1', 'up']]

I want the output like that:我想要这样的 output:

Message 1
65 0 Hello 
65 1 world
Message 2
78 0 what's
78 1 up

In general it's not a great idea to try to modify a list as you're iterating over it, because it's very easy to confuse yourself.一般来说,在遍历列表时尝试修改列表并不是一个好主意,因为这很容易让自己感到困惑。 Since you just want to print the list contents with extra messages interspersed, I think it's better to just not modify the list and print the messages as you iterate.由于您只想打印带有额外消息的列表内容,我认为最好不要修改列表并在迭代时打印消息。

The easy way to group things according to specific criteria (in this case the 0th index of each list) is to use itertools.groupby :根据特定标准(在本例中为每个列表的第 0 个索引)对事物进行分组的简单方法是使用itertools.groupby

>>> from itertools import groupby
>>> for i, (_, group) in enumerate(groupby(sorted_list, lambda i: i[0])):
...     print(f"Message {i+1}")
...     for line in group:
...         print(" ".join(line))
...
Message 1
65 1 Hello
65 2 world
Message 2
78 2 what's
78 3 up

Also you can do it using pandas :您也可以使用pandas来做到这一点:

import pandas as pd

sorted_list = [['65', '0', 'Hello'],
['65', '1', 'world'],
['78', '0', "what's"],
['78', '1', 'up']]

df = pd.DataFrame(sorted_list)
groups = df.groupby(0) #group by first column

for i,(name, group) in enumerate(groups):
  print('Message {0}'.format(i+1))
  for c1, c2, c3 in group.to_numpy():
    print(c1,c2,c3)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM