我如何 align/merge 2 个列表? (Python)
How do I align/merge 2 lists? (Python)
我真的不知道如何描述这个,但在我可怕的解释之后,我会在预格式化的文本中包含一个输出。
所以...我创建了三个列表,我需要使用两个列表,'employeeSold' 和 'employeeName,' 但是我需要 merge/align 这两个列表,这样我就可以建立一个排名系统来确定谁拥有最多,我想出了如何为 employeeSold 从最大到最重要的顺序排序,但我最不确定如何 link 正确的名称到正确的值,我认为它需要在排序之前出现,但我真的不知道知道要输入什么,我花了几个小时思考它。
这是我想要的代码输出示例:
Ranking:
John - 5
Laura - 4
BOJO -1
它已将每个整数 (employeeSold) 分配给每个字符串 (employeeName),然后将用户插入的整数 (employeeSold) 从大到高排序,然后在整数旁边打印他们的名字。
这是我的代码:
def employee():
employeeName = input("What is Employee's name?: ")
employeeID = input("What is Employee's ID?: ")
employeeSold = int(input("How many houses employee sold?: "))
nameList.append(employeeName)
idList.append(employeeID)
soldList.append(employeeSold)
nextEmployee = input("Add another employee? Type Yes or No: ")
if nextEmployee == "2":
employee()
else:
print("Employee Names:")
print(", ".join(nameList))
print("Employee's ID: ")
print(", ".join(idList))
print("Employee Sold:")
print( " Houses, ".join( repr(e) for e in soldList ), "Houses" )
print("Commission: ")
employeeCommission = [i * 500 for i in soldList]
print(", ".join( repr(e) for e in employeeCommission ), "" )
print("Commission Evaluation: ")
totalCommission = sum(employeeCommission)
print(totalCommission)
soldList.sort(reverse=True)
print("Employee Ranking: ")
ranking = (", ".join( repr(e) for e in soldList))
print(ranking)
nameList = []
idList = []
soldList = []
employee()```
--------
Any help would be very much so appreciated.
您可以考虑将您的逻辑分解为多个函数和 names
sorting a zip,以及 num_houses_sold
列表以打印排名正如您指定的那样:
def get_int_input(prompt: str) -> int:
num = -1
while True:
try:
num = int(input(prompt))
break
except ValueError:
print('Error: Enter an integer, try again...')
return num
def get_yes_no_input(prompt: str) -> bool:
allowed_responses = {'y', 'yes', 'n', 'no'}
user_input = input(prompt).lower()
while user_input not in allowed_responses:
user_input = input(prompt).lower()
return user_input[0] == 'y'
def get_single_employee_info(names: list[str], ids: list[int],
num_sold_houses: list[int]) -> None:
names.append(input('What is the employee\'s name?: '))
ids.append(get_int_input('What is the employee\'s id?: '))
num_sold_houses.append(
get_int_input('How many houses did the employee sell?: '))
def get_houses_sold_info(names: list[str], ids: list[int],
num_sold_houses: list[int]) -> None:
get_single_employee_info(names, ids, num_sold_houses)
add_another_employee = get_yes_no_input('Add another employee [yes/no]?: ')
while add_another_employee:
get_single_employee_info(names, ids, num_sold_houses)
add_another_employee = get_yes_no_input(
'Add another employee [yes/no]?: ')
def print_entered_info(names: list[str], ids: list[int],
num_sold_houses: list[int]) -> None:
print()
row_width = 12
comission_per_house = 500
header = ['Name', 'Id', 'Houses Sold', 'Commission']
print(' '.join(f'{h:<{row_width}}' for h in header))
commission = [n * comission_per_house for n in num_sold_houses]
for values in zip(*[names, ids, num_sold_houses, commission]):
print(' '.join(f'{v:<{row_width}}' for v in values))
print()
total_commission = sum(commission)
print(f'Total Commission: {total_commission}')
print()
rankings = sorted(zip(num_sold_houses, names), reverse=True)
print('Ranking:')
for houses_sold, name in rankings:
print(f'{name} - {houses_sold}')
def main() -> None:
print('Houses Sold Tracker')
print('===================')
names, ids, num_houses_sold = [], [], []
get_houses_sold_info(names, ids, num_houses_sold)
print_entered_info(names, ids, num_houses_sold)
if __name__ == '__main__':
main()
用法示例:
Houses Sold Tracker
===================
What is the employee's name?: Laura
What is the employee's id?: 1
How many houses did the employee sell?: a
Error: Enter an integer, try again...
How many houses did the employee sell?: 4
Add another employee [yes/no]?: yes
What is the employee's name?: John
What is the employee's id?: 2
How many houses did the employee sell?: 5
Add another employee [yes/no]?: y
What is the employee's name?: BOJO
What is the employee's id?: 3
How many houses did the employee sell?: 1
Add another employee [yes/no]?: no
Name Id Houses Sold Commission
Laura 1 4 2000
John 2 5 2500
BOJO 3 1 500
Total Commission: 5000
Ranking:
John - 5
Laura - 4
BOJO - 1
顺便说一句,如果你做过真实的东西,不要使用连续的用户 ID,你可以通过监控获得的信息量是疯狂的,例如,用户获取率,您不希望外部人员能够弄清楚。
您可以使用压缩功能合并列表,然后自定义键排序。
SortByName 函数返回排序键名称和 SortBySalary 函数返回键 salary
def SortByName(FullList):
return FullList[0]
def SortBySalary(FullList):
return FullList[2]
NamesList=['John','Laura','Bojo']
IdList=[1,2,5]
SalaryList=[2000,1000,5000]
ZippedList=zip(NamesList,IdList,SalaryList)
print ZippedList
# result
#[('John', 1, 2000), ('Laura', 2, 1000), ('Bojo', 5, 5000)]
ZippedList.sort(key=SortByName,reverse=True)
print ZippedList
# result
# [('Laura', 2, 1000), ('John', 1, 2000), ('Bojo', 5, 5000)]
ZippedList.sort(key=SortBySalary,reverse=True)
print ZippedList
# result
# [('Bojo', 5, 5000), ('John', 1, 2000), ('Laura', 2, 1000)]
以后如果想按id排序列表,只需要实现id排序函数即可。
def SortByID(FullList):
return FullList[1]
ZippedList.sort(key=SortByID)
我真的不知道如何描述这个,但在我可怕的解释之后,我会在预格式化的文本中包含一个输出。 所以...我创建了三个列表,我需要使用两个列表,'employeeSold' 和 'employeeName,' 但是我需要 merge/align 这两个列表,这样我就可以建立一个排名系统来确定谁拥有最多,我想出了如何为 employeeSold 从最大到最重要的顺序排序,但我最不确定如何 link 正确的名称到正确的值,我认为它需要在排序之前出现,但我真的不知道知道要输入什么,我花了几个小时思考它。
这是我想要的代码输出示例:
Ranking:
John - 5
Laura - 4
BOJO -1
它已将每个整数 (employeeSold) 分配给每个字符串 (employeeName),然后将用户插入的整数 (employeeSold) 从大到高排序,然后在整数旁边打印他们的名字。
这是我的代码:
def employee():
employeeName = input("What is Employee's name?: ")
employeeID = input("What is Employee's ID?: ")
employeeSold = int(input("How many houses employee sold?: "))
nameList.append(employeeName)
idList.append(employeeID)
soldList.append(employeeSold)
nextEmployee = input("Add another employee? Type Yes or No: ")
if nextEmployee == "2":
employee()
else:
print("Employee Names:")
print(", ".join(nameList))
print("Employee's ID: ")
print(", ".join(idList))
print("Employee Sold:")
print( " Houses, ".join( repr(e) for e in soldList ), "Houses" )
print("Commission: ")
employeeCommission = [i * 500 for i in soldList]
print(", ".join( repr(e) for e in employeeCommission ), "" )
print("Commission Evaluation: ")
totalCommission = sum(employeeCommission)
print(totalCommission)
soldList.sort(reverse=True)
print("Employee Ranking: ")
ranking = (", ".join( repr(e) for e in soldList))
print(ranking)
nameList = []
idList = []
soldList = []
employee()```
--------
Any help would be very much so appreciated.
您可以考虑将您的逻辑分解为多个函数和 names
sorting a zip,以及 num_houses_sold
列表以打印排名正如您指定的那样:
def get_int_input(prompt: str) -> int:
num = -1
while True:
try:
num = int(input(prompt))
break
except ValueError:
print('Error: Enter an integer, try again...')
return num
def get_yes_no_input(prompt: str) -> bool:
allowed_responses = {'y', 'yes', 'n', 'no'}
user_input = input(prompt).lower()
while user_input not in allowed_responses:
user_input = input(prompt).lower()
return user_input[0] == 'y'
def get_single_employee_info(names: list[str], ids: list[int],
num_sold_houses: list[int]) -> None:
names.append(input('What is the employee\'s name?: '))
ids.append(get_int_input('What is the employee\'s id?: '))
num_sold_houses.append(
get_int_input('How many houses did the employee sell?: '))
def get_houses_sold_info(names: list[str], ids: list[int],
num_sold_houses: list[int]) -> None:
get_single_employee_info(names, ids, num_sold_houses)
add_another_employee = get_yes_no_input('Add another employee [yes/no]?: ')
while add_another_employee:
get_single_employee_info(names, ids, num_sold_houses)
add_another_employee = get_yes_no_input(
'Add another employee [yes/no]?: ')
def print_entered_info(names: list[str], ids: list[int],
num_sold_houses: list[int]) -> None:
print()
row_width = 12
comission_per_house = 500
header = ['Name', 'Id', 'Houses Sold', 'Commission']
print(' '.join(f'{h:<{row_width}}' for h in header))
commission = [n * comission_per_house for n in num_sold_houses]
for values in zip(*[names, ids, num_sold_houses, commission]):
print(' '.join(f'{v:<{row_width}}' for v in values))
print()
total_commission = sum(commission)
print(f'Total Commission: {total_commission}')
print()
rankings = sorted(zip(num_sold_houses, names), reverse=True)
print('Ranking:')
for houses_sold, name in rankings:
print(f'{name} - {houses_sold}')
def main() -> None:
print('Houses Sold Tracker')
print('===================')
names, ids, num_houses_sold = [], [], []
get_houses_sold_info(names, ids, num_houses_sold)
print_entered_info(names, ids, num_houses_sold)
if __name__ == '__main__':
main()
用法示例:
Houses Sold Tracker
===================
What is the employee's name?: Laura
What is the employee's id?: 1
How many houses did the employee sell?: a
Error: Enter an integer, try again...
How many houses did the employee sell?: 4
Add another employee [yes/no]?: yes
What is the employee's name?: John
What is the employee's id?: 2
How many houses did the employee sell?: 5
Add another employee [yes/no]?: y
What is the employee's name?: BOJO
What is the employee's id?: 3
How many houses did the employee sell?: 1
Add another employee [yes/no]?: no
Name Id Houses Sold Commission
Laura 1 4 2000
John 2 5 2500
BOJO 3 1 500
Total Commission: 5000
Ranking:
John - 5
Laura - 4
BOJO - 1
顺便说一句,如果你做过真实的东西,不要使用连续的用户 ID,你可以通过监控获得的信息量是疯狂的,例如,用户获取率,您不希望外部人员能够弄清楚。
您可以使用压缩功能合并列表,然后自定义键排序。 SortByName 函数返回排序键名称和 SortBySalary 函数返回键 salary
def SortByName(FullList):
return FullList[0]
def SortBySalary(FullList):
return FullList[2]
NamesList=['John','Laura','Bojo']
IdList=[1,2,5]
SalaryList=[2000,1000,5000]
ZippedList=zip(NamesList,IdList,SalaryList)
print ZippedList
# result
#[('John', 1, 2000), ('Laura', 2, 1000), ('Bojo', 5, 5000)]
ZippedList.sort(key=SortByName,reverse=True)
print ZippedList
# result
# [('Laura', 2, 1000), ('John', 1, 2000), ('Bojo', 5, 5000)]
ZippedList.sort(key=SortBySalary,reverse=True)
print ZippedList
# result
# [('Bojo', 5, 5000), ('John', 1, 2000), ('Laura', 2, 1000)]
以后如果想按id排序列表,只需要实现id排序函数即可。
def SortByID(FullList):
return FullList[1]
ZippedList.sort(key=SortByID)