使用Python更改Lis的顺序

2024-05-13 10:14:46 发布

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

我对Python还不熟悉。。你知道吗

我有一个列表(名称.txt)这是四个名称:

  • 科林
  • 加里
  • 吉比
  • 罗斯

我想从文件中输出列表,然后将名称的顺序更改一个空格,并将输出保存在原始的名称.txt“文件。你知道吗

Run1 would be: Colin Gary Gibby Ross

Run2 would be: Gary Gibby Ross Colin

Run3 would be: Gibby Ross Colin Gary

……等等。你知道吗

到目前为止,我的代码能够将文件和输出作为列表,但我不知道如何将顺序移动1位并再次保存:

#!/usr/bin/python

# Open a file
with open ('names.txt', 'r') as f:
  list1 = f.read().splitlines()
  for item1 in list1[0:4]:
   print (item1)
f.close()

感谢大家的帮助。谢谢。你知道吗


Tags: 文件txt名称列表顺序be空格item1
3条回答

这将读取中现有的names.txt文件并显示内容。然后将顺序更改为1,并将生成的列表写回同一个文件:

with open('names.txt', 'r') as f:
    list1 = f.read().splitlines()
    print('\n'.join(list1))
    list1 = list1[1:] + list1[:1]

with open('names.txt', 'w') as f:
    f.write('\n'.join(list1))

运行1

Colin
Gary
Gibby
Ross

运行2

Gary
Gibby
Ross
Colin

只需在循环中打印从索引1开始的所有内容。最后打印索引0

for i in range(1:len(list1)):
    print(list1[i])
print(list1[0])

或者,如果您需要将其列入新列表:

list1 = list1[1:] + list1[:1]

This答案详细说明了如何使用collections.deque来移动列表,他们认为这是为“两端推拉”而优化的,为了方便起见,我在下面提供了示例代码。你知道吗

from collections import deque
items = deque([1, 2])
items.append(3) # deque == [1, 2, 3]
items.rotate(1) # The deque is now: [3, 1, 2]
items.rotate(-1) # Returns deque to original state: [1, 2, 3]
item = items.popleft() # deque == [2, 3] 

相关问题 更多 >