Python:按预先设定的索引重新排列列表

2024-09-26 17:37:57 发布

您现在位置:Python中文网/ 问答频道 /正文

所以我想把一个有3行的输入文件放进去。 第一行是列表中的项目数 第二行,关于如何重新排列列表的索引。(详见下文) 第三行,数字列表本身

所以从第二行开始在.txt中是重新排列的列表的索引。很难解释,但这就是它的工作原理(参见在.txt中(供参考) 第一个数不变,第二个数变为第三个数,第五个数变为第二个数,第四个数变为第五个数,以此类推

以下是一些示例输入: 在.txt中你知道吗

5
1 3 4 5 2
12 33 96 84 74

你知道吗输出.txt你知道吗

12
74
33
96
84

以下是程序本身:

fin = open('in.txt','r') #file in
fout = open('output.txt','w') #file out

indata = fin.readlines()
cownum = int(indata[0])
print(cownum)
posmove = indata[1]
cid = indata[2]

poss=posmove.split()
ids=cid.split()

print(poss)
print("")

i=0
while i != int(cownum):
  print(poss[i])
  ids.insert((int(poss[i])-1), ids.pop(i))
  i=i+1
  print(i)
  print(ids)


newids = str(ids)
fout.write(newids)


fin.close()
fout.close()

只是一些背景信息,列表中的数字将有点像产品id的

现在的问题是我重新排列了两次项目。

抱歉,如果我有点不清楚(lol和奇怪的变量名)


Tags: intxtids列表数字openfileint
3条回答

你可以试试这个:

file_data = [map(int, i.strip('\n').split()) for i in open('filename.txt')]
new_data = [i[-1] for i in sorted(zip(file_data[1], file_data[-1]), key=lambda x:x[0])]

输出:

[12, 74, 33, 96, 84]

将文件读入列表后,可以使用以下代码对其进行排序:

>>> indexes = [1, 3, 4, 5, 2]
>>> values = [12, 33, 96, 84, 74]
>>> newlist = [0, 0, 0, 0, 0]
...
...
>>> for x, y in zip(indexes, values):
...     newlist[x-1] = y
... 
>>> for x in newlist:
...     print(x)
... 
12
74
33
96
84

假设您已经成功地提取了位置列表和产品ID列表(仍然需要将数据转换为整数):

positions = [1, 3, 4, 5, 2]
product_ids = [12, 33, 96, 84, 74]

您可以使用名为decorate-sort-undecorate的模式按给定位置对产品ID进行排序:

>>> [prod_id for (pos, prod_id) in sorted(zip(positions, product_ids))]
[12, 74, 33, 96, 84]

逐步解释:

我们首先用相应的位置装饰产品标识列表:

>>> zip(positions, product_ids)
[(1, 12), (3, 33), (4, 96), (5, 84), (2, 74)]

然后我们对修饰列表进行排序,这将给我们一个正确的顺序,因为元组是按项排序的,因为第一项是一个位置,这就给了我们想要的顺序。你知道吗

>>> sorted(zip(positions, product_ids))
[(1, 12), (2, 74), (3, 33), (4, 96), (5, 84)]

最后,我们取消装饰(解包)现在排序的元组列表,以获得按所需顺序排列的产品ID列表(同时丢弃它们的位置信息):

>>> [prod_id for (pos, prod_id) in sorted(zip(positions, product_ids))]
[12, 74, 33, 96, 84]

(用于演示的Python2)

相关问题 更多 >

    热门问题