所以我想把一个有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和奇怪的变量名)
你可以试试这个:
输出:
将文件读入列表后,可以使用以下代码对其进行排序:
假设您已经成功地提取了位置列表和产品ID列表(仍然需要将数据转换为整数):
您可以使用名为decorate-sort-undecorate的模式按给定位置对产品ID进行排序:
逐步解释:
我们首先用相应的位置装饰产品标识列表:
然后我们对修饰列表进行排序,这将给我们一个正确的顺序,因为元组是按项排序的,因为第一项是一个位置,这就给了我们想要的顺序。你知道吗
最后,我们取消装饰(解包)现在排序的元组列表,以获得按所需顺序排列的产品ID列表(同时丢弃它们的位置信息):
(用于演示的Python2)
相关问题 更多 >
编程相关推荐