简体   繁体   English

如何对齐/合并 2 个列表? (Python)

[英]How do I align/merge 2 lists? (Python)

I really do not know how to describe this but I'll include an output in preformatted text after my horrific explanation.我真的不知道如何描述这一点,但在我可怕的解释之后,我会在预格式化的文本中包含一个输出。 So... I create three lists I need to use two, 'employeeSold' and 'employeeName,' however I need to merge/align the two so I can make a ranking system on who's got the most, I figured out how to order from largest to most significant for employeeSold, but I am most unsure on how to link the correct Name to the correct value, I figured it needs to come before the ordering though, but I really do not know what to type and I've spent a handful of hours thinking about it.所以...我创建了三个列表,我需要使用两个,'employeeSold' 和 'employeeName',但是我需要合并/对齐这两个,这样我就可以建立一个关于谁获得最多的排名系统,我想出了如何订购对于employeeSold 从最大到最重要,但我最不确定如何将正确的名称链接到正确的值,但我认为它需要在订购之前出现,但我真的不知道该输入什么,我已经花了几个小时的思考。


Here is an example OUTPUT of what I want for this code:这是我想要此代码的示例输出:

Ranking:
John - 5
Laura - 4
BOJO -1

It has assigned each integer (employeeSold) to each string (employeeName) and then ordered the integers (employeeSold) inserted by the user from largest to most significant and then printed their names next to their integer.它将每个整数 (employeeSold) 分配给每个字符串 (employeeName),然后将用户插入的整数 (employeeSold) 从最大到最重要排序,然后在整数旁边打印它们的名称。


Here is my code:这是我的代码:

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.

You could consider breaking up your logic into multiple functions andsorting a zip of the names , and num_houses_sold list to print a ranking as you specified:你可以考虑打破你的逻辑分为多个功能和分拣一个拉链的的names ,并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()

Example Usage:示例用法:

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

As an aside if you ever make something real don't use a sequential user id, the amount of information you can obtain from just monitoring this is insane, eg, the rate of user acquisition, which you don't want external people to be able to figure out.顺便说一句,如果你曾经做过一些真实的事情,不要使用连续的用户 ID,你可以通过监控获得的信息量是疯狂的,例如,用户获取率,你不希望外部人员成为能够弄清楚。

You can use zip function to merge lists and then custom key sorting.您可以使用 zip 功能合并列表,然后自定义键排序。 SortByName function returning the sort key name and SortBySalary function returning key salary SortByName 函数返回排序键名称和 SortBySalary 函数返回键工资

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

If you later want to sort the lists by id, just implement id sorting function.如果您以后想按 id 对列表进行排序,只需实现 id 排序功能。

def SortByID(FullList):
    return FullList[1]

ZippedList.sort(key=SortByID)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM