我有一个包含内容的文本文件:
A;B;C;D
a;b;c;d
我正在读取python中的文件,并希望重新排列列,例如 -
B;C;D;A
b;c;d;a
我试过阅读专栏 -
file = open('add.txt','r')
text = file.read()
column1 = x[0] for x in text
但这并没有帮助。所以我需要一种方法来转换它。
答案 0 :(得分:2)
您可以使用csv模块将文件读入列表,然后只需重新编制列表顺序索引。
import csv
list_variable = []
with open("file.txt") as add_txt:
reader = csv.reader(add_txt, delimiter =';')
for line in reader:
line += [line.pop(0)]
list_variable.append(line)
答案 1 :(得分:0)
您可以使用元组/可迭代解包来执行此操作
# Create a palette of 4 colors of hues from 0 to 360, saturations between
# 0.1 and 0.5, and lightness from 0.6 to 0.85
pal <- qualpal(n = 4, list(h = c(0, 360), s = c(0.1, 0.5), l = c(0.6, 0.85)))
# Look at the colors in hex format
pal$hex
#> [1] "#6F75CE" "#CC6B76" "#CAC16A" "#76D0D0"
# Create a palette using one of the predefined color subspaces
pal2 <- qualpal(n = 4, colorspace = "pretty")
# Distance matrix of the DIN99d color differences
pal2$de_DIN99d
#> #69A3CC #6ECC6E #CA6BC4
#> 6ECC6E 22
#> CA6BC4 21 30
#> CD976B 24 21 21
plot(pal2)
答案 2 :(得分:0)
您不需要使用csv
模块作为建议的答案:
with open('add.txt', 'r') as file:
text = file.read()
result = []
for line in text.splitlines():
cols = line.split(';')
cols = cols[1:] + [cols[0]]
result.append(cols)
print(result)
输出:
[['B', 'C', 'D', 'A'], ['b', 'c', 'd', 'a']]