Python将列表重新排列为元组

时间:2013-11-27 13:38:34

标签: python tuples

我有以下代码:

def ex1():

b= input("Please enter a file name to be opened: ")
a = (b+".txt")

c =[]

def employee(lanme,oname,num,title,salary):
    c.append(employee)

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()

它的作用基本上是读取包含员工信息的文本文件。 例如: 文本文件的格式为:(num,salary,position,oname,lname)

15674 24000 Manager Gregory the 1st John , 
14522 24500 Team Leader Baker George ,
22422 24352 Crew member house bob

我需要从文本文件中获取信息,然后将其重新排列为def employee function中的格式。 这是(lanme,oname,num,title,salary)来自原始的(num,salary,position,oname,lname)。

我知道这样做的方法,但它需要存储为元组,可以单独访问或作为整个项目访问。

如果这个问题看起来很难解释,我很抱歉,但我尽力了。

2 个答案:

答案 0 :(得分:0)

for items in data:
  id, salary, title, lastname, firstname = items
  employee(lastna,e, firstname, id, title, salary)

答案 1 :(得分:0)

除了Alex所说的,你的employee功能肯定没有达到你想要的效果。现在它将自己的引用添加到c,因此c将是[<employee function>, <employee function>, ...]之类的列表 如果您想要一个由元组表示的员工,请让该函数返回元组。

def employee(lanme, oname, num,title,salary):
    return (lanme, oname, num, title, salary)

编辑:

为了解释Alex的答案,我们将列表解压缩为变量并从解压缩列表中创建一个新元组。这是一个简单的例子

mylist = [0, 1, 2, 3, 4]
a, b, c, d, e = mylist # a=0, b=1, ...
mytuple = (e, d, c, b, a) # mytuple = (4, 3, 2, 1, 0)

通过这些更改,您的脚本看起来像

b = input("Please enter a file name to be opened: ")
a = b + '.txt'

def employee(lname, oname, num, title, salary):
    return (lname, oname, num, title, salary)

def readfile(a):

    # Instead of the try/except block
    # you can use a with statement
    with open(a, 'r') as check:
        data = []

        # You can also skip the readlines()
        # and iterate over the file directly
        for items in check:

            # This is unpacking, see the note above
            # Also, based on your example file **this won't work**, see below note
            num, salary, position, oname, lname = items.split()
            newemployee = employee(lname, oname, num, title, salary)
            data.append(newemployee)
    return data

myemployees = readfile(a)

最后,items.split()也可能不是你想要的。 如果你有15674 24000 Manager Gregory the 1st John ,行,那么使用split会给你['15674', '24000', 'Manager', 'Gregory', 'the', '1st', 'John' ','],而你想要的列表是`[&#39; 15674&#39;,&#39; 24000&#39 ;,&#39;经理&#39;,&#39; Gregory the 1st&#39;,&#39; John&#39;]。

获取该列表取决于您的文件结构,这似乎不一致使其变得困难。用空格分隔的字段,有些字段是多个单词,有时候是逗号尾随。