如何在Python中更改元组项目的顺序?

时间:2019-12-04 12:02:24

标签: python string function tuples

我真的很坚持。我必须创建两个函数。第一个将字符串作为参数,然后创建并返回一个元组。该字符串具有以下格式:fisrt_name,last_name,salary。但是,我必须将订单更改为薪金,名字,姓氏。关于如何做的任何想法?这是我到目前为止的内容:

def function_one(person_string):
    first_name, last_name, salary=person_string.split('')
    return salary, first_name, last_name

def function_two(person_tuple):
    string_person = ' '.join(person_tuple)
    return string_person

path_to_file = 'person.txt'
with open(path_to_file, 'r') as file
    content = file.read()

print(content)

with open(path_to_file, 'r') as file:
    for line in file.readlines():
        tuple_person = string_to_tuple(line)
        print(tuple_person)

2 个答案:

答案 0 :(得分:1)

您可以这样尝试

def function_one(person_string):
    data = person_string.split(' ')
    return (data[2], data[0], data[1])

def function_two(person_tuple):
    string_person = ' '.join(person_tuple)
    return string_person
Jhon = 'Jhon Smith 100000'
string = function_one(Jhon)
out    = function_two(string)
print(string, out)

out:('100000', 'Jhon', 'Smith') 100000 Jhon Smith

答案 1 :(得分:1)

您可以做这样的事情吗?

peoples = ["jordan lee 21", "megan bob 35",]
peoples_2 = []

for people in peoples:
    first_name, last_name, salary = people.split()
    peoples_2.append('{} {} {}'.format(salary, first_name, last_name))

print(peoples_2)

如果您真的需要它成为一个元组或列表,只需将其转换

tuple(peoples_2)

只需将硬编码的人员列表替换为以前获取列表的方式即可。