我已经问了同样的问题,但我觉得我说的是非常模糊的。 基本上我需要改变:
data =
[['15674' '24000' 'Manager' 'Gregory the 1st' 'John'],
['15674' '24000' 'Manager' 'Gregory the 1st' 'John'],
['15674' '24000' 'Manager' 'Gregory the 1st' 'John'],
['15674' '24000' 'Manager' 'Gregory the 1st' 'John']]
data = [number, salary,position, othernames, firstname]
进入:
data1=
('John', 'Gregory the 1st',15674,'Manager',24000),
('John', 'Gregory the 1st',15674,'Manager',24000),
('John', 'Gregory the 1st',15674,'Manager',24000,)
('John', 'Gregory the 1st',15674,'Manager',24000)
data1 = (Firstname, othernames, number, position,salary)
我已经重复了这一点,以表明我可以获得一个包含100名员工的文件,这些文件需要重新排列并按顺序打印出来作为元组。所有项目都具有相同的位置,例如number[0]
,salary[1]
,position [2]
然而,其他名称的中间部分可能有多个名称,因此它没有明确的位置。但是,名字只有一个项目,因此可以找到list1[-1]
。
def ex1 ():
b= input("Please enter a file name to be opened: ")
a = (b+".txt")
data =[]
def employee(lanme, oname, num,title,salary):
return (lanme, oname, num, title, salary)
def readfile(a):
try:
data =[]
check = open(a, 'r')
line =check.readlines()
for items in line:
breakup= items.split()
data.append(breakup)
except IOError as e :
print("Failed to open", fileName)
readfile(a)
ex1()
答案 0 :(得分:3)
如果输入数据有效,则可以轻松完成重新排序。
# First, Last, Number, Position, Salary
data = [(f,l,n,p,s) for n,s,p,l,f in data]
仅当您的输入值是列表列表时才会起作用。您的样本无效。
答案 1 :(得分:0)
我的解决方案是列表清单,但很简单。
data = ["15674 24000 Manager Gregory the 1st John", "15674 24000 Manager Gregory the 1st John",
"15674 24000 Manager Gregory the 1st John", "15674 24000 Manager Gregory the 1st John"]
data1 = []
for items in data:
splitNames = items.split()
number, salary, position, first, des1, des2, last = splitNames
data1.append([last, first + ' ' + des1 + ' ' + des2, number, position, salary])
for items in data1:
print items
<强>结果:强>
['John', 'Gregory the 1st', '15674', 'Manager', '24000']
['John', 'Gregory the 1st', '15674', 'Manager', '24000']
['John', 'Gregory the 1st', '15674', 'Manager', '24000']
['John', 'Gregory the 1st', '15674', 'Manager', '24000']
这不是最好的解决方案,我这样写,所以它很容易理解,因为它是基本的操作。
<强>元组:强>
如果你想要它是tupels列表只需重写这一行:
data1.append(tuple([last, first + ' ' + des1 + ' ' + des2, number, position, salary]))
使用tuple()从python docs看到解释here。
<强>结果:强>
('John', 'Gregory the 1st', '15674', 'Manager', '24000')
('John', 'Gregory the 1st', '15674', 'Manager', '24000')
('John', 'Gregory the 1st', '15674', 'Manager', '24000')
('John', 'Gregory the 1st', '15674', 'Manager', '24000')
适应您的代码:
for items in line:
breakup= items.split()
number, salary, position, first, des1, des2, last = breakup
data.append(tuple([last, first + ' ' + des1 + ' ' + des2, number, position, salary]))
print data
<强>结果:强>
[('John', 'Gregory the 1st', '15674', 'Manager', '24000'), ('John', 'Gregory the 1st', '15674', 'Manager', '24000'), ('John', 'Gregory the 1st', '15674', 'Manager', '24000'), ('John', 'Gregory the 1st', '15674', 'Manager', '24000')]