【问题标题】:In Python, how do I replace certain integers in a list with other integers?在 Python 中,如何用其他整数替换列表中的某些整数?
【发布时间】:2020-05-28 02:50:01
【问题描述】:

我是 Python 新手。

我有一个数字列表:lst=[1, 7, 2, 10, 20, 4]

我正在尝试替换列表中的前三个数字(7、10 和 20) 分别为 3.5、5 和 10。

这是我到目前为止的代码。 我可以计算一半,但不知道如何替换列表中的数字。

lst=[1, 7, 2, 10, 20, 4]

maxvalue1 = max(1, 7, 2, 10, 20, 4) 打印(最大值1)

maxvalue2 = max(1, 7, 2, 10, 4) 打印(最大值2)

最大值3 = 最大值(1, 2, 4, 7) 打印(最大值3)

一半最大值1=最大值1/2 打印(Halfofmaxvalue1)

一半最大值2=最大值2/2 打印(Halfofmaxvalue2)

一半最大值3=最大值3/2 打印(Halfofmaxvalue3)

【问题讨论】:

    标签: integer


    【解决方案1】:

    您可以执行以下操作:

    list = [1, 2, 3, 4, 5, 11, 23, 1, 312, 123, 121]
    
    # sort the list so that the largest are first
    list = sorted(list, reverse=True)
    # get the 3 largest
    max3 = list[0:3]
    # if the value x is one of the largest divide it by 2, else keep it the same
    l = [x//2 if x in max3 else x for x in list]
    
    print(list) # before replacement
    print(l) # after replacement
    

    输出:

    [312, 123, 121, 23, 11, 5, 4, 3, 2, 1, 1]
    [156, 61, 60, 23, 11, 5, 4, 3, 2, 1, 1]
    

    【讨论】:

      猜你喜欢
      • 2021-09-07
      • 2020-05-22
      • 1970-01-01
      • 2022-01-23
      • 2021-06-17
      • 2018-04-24
      • 2017-12-02
      • 2019-07-04
      • 1970-01-01
      相关资源
      最近更新 更多