【问题标题】:How do I align/merge 2 lists? (Python)如何对齐/合并 2 个列表? (Python)
【发布时间】:2021-12-20 00:43:41
【问题描述】:

我真的不知道如何描述这一点,但在我可怕的解释之后,我将在预格式化文本中包含一个输出。 所以...我创建了三个列表,我需要使用两个,“employeeSold”和“employeeName”,但是我需要合并/对齐这两个列表,这样我就可以建立一个关于谁获得最多的排名系统,我想出了如何订购对于employeeSold,从最大到最重要,但我最不确定如何将正确的名称链接到正确的值,我认为它需要在订购之前出现,但我真的不知道输入什么,我已经花了想了几个小时。


这是我想要的代码的示例输出:

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.

【问题讨论】:

  • 对列表使用 zip 函数,然后自定义键排序

标签: python arrays list integer alignment


【解决方案1】:

您可以使用 zip 功能来合并列表,然后自定义键排序。 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)]

如果你以后想按id对列表进行排序,只需实现id排序功能即可。

def SortByID(FullList):
    return FullList[1]

ZippedList.sort(key=SortByID)

【讨论】:

    【解决方案2】:

    您可以考虑将您的逻辑分解为多个函数和 sorting 一个 zip namesnum_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,你可以从监控中获得的信息量是疯狂的,例如,用户获取率,你不这样做'不希望外部人员能够弄清楚。

    【讨论】:

      猜你喜欢
      • 2022-06-28
      • 1970-01-01
      • 2021-03-24
      • 2015-09-21
      • 2023-02-10
      • 1970-01-01
      • 2020-01-10
      • 2013-01-17
      • 1970-01-01
      相关资源
      最近更新 更多