输入进入列表的元组

时间:2016-03-18 00:31:57

标签: python list tuples

我试图将用户的输入转换为进入列表的元组。我使用split方法,但它似乎接受输入并在列表中创建一个元组,但也在列表中创建了另一个...我希望这是有意义的......无论如何,我运行它在可视化工具中,看到每个都有一个索引为0和1,所以我想我有一个小细节outta whack。

简而言之: 输入员工的姓名。 (最后,第一) 并且该姓氏,名字被转换为元组并发送给 名单。

我认为列表中有两个值的员工会更好地作为列表中的元组,对吗?让我知道,如果我刚刚关闭,它作为一个简单的列表更好。 无论如何,这里是代码:

empList = []
empName = input("Please enter employee name. (Last name, First name):\n")
nameSplit = tuple(empName.split(","))
empList += nameSplit
salary = float(input("Please enter salary for " +str(empList[0:]) + ":\n" ))
grossSalary = salary

if (grossSalary > 100000):
    fedTax = (grossSalary * .2)
else:
    fedTax = (grossSalary * .15)

stateTax = (grossSalary * .05)
netSalary = (grossSalary - (fedTax + stateTax))

print('''\nGross Salary: {0:>5.2f} \n 
Federal Tax: {minus:>2}{1:>6.2f} \n 
State Tax: {minus:>4}{2:>4.2f} \n 
Net Salary: {3:>10.2f}'''.format(grossSalary, fedTax, stateTax, netSalary,
minus = "-"))

2 个答案:

答案 0 :(得分:2)

empList = []
empName = input("Please enter employee name. (Last name, First name):\n")
nameSplit = tuple(empName.split(","))
empList += nameSplit

最后一行empList += nameSplit将每个项目从元组添加/连接到列表。它不会添加元组本身:

>>> l = [1, 2, 3]
>>> l += (4, 5)
>>> l
[1, 2, 3, 4, 5]

您应该使用list.append()代替:

empList.append(nameSplit)

现在它会附加元组:

>>> empList = []
>>> empName = 'Lastname, Firstname'
>>> nameSplit = tuple(empName.split(","))
>>> empList.append(nameSplit)
>>> empList
[('Lastname', ' Firstname')]

>>> empName = 'Else, Someone'
>>> nameSplit = tuple(empName.split(","))
>>> empList.append(nameSplit)
>>> empList
[('Lastname', ' Firstname'), ('Else', ' Someone')]

另一件事。空格保留在使用,分割的字符串中。您应该在将每个字符串添加到列表之前删除它们,并且您实际上不需要中间变量:

empList.append(tuple(s.strip() for s in empName.split(",")))

答案 1 :(得分:0)

以下是您的实际代码(python3)的示例会话

Please enter employee name. (Last name, First name):
Payne,Max
Please enter salary for ['Payne', 'Max']:
100000

Gross Salary: 100000.00 

Federal Tax:  -15000.00 

State Tax:    -5000.00 

Net Salary:   80000.00

因此,我唯一要做的修改是

salary = float(input("Please enter salary for " + empList[1] + " " + empList[0] + ":\n" ))

除非您的评论input = (Payne, Max),您是否希望用户输入括号?这将在列表中生成元组。无论如何,在你的程序empList中可以是一个元组或一个列表,这没关系。