【问题标题】:Renaming items in python list [duplicate]重命名python列表中的项目[重复]
【发布时间】:2019-04-27 22:08:37
【问题描述】:

我有一个 python 列表如下:

['item1','item2','item3'] 

我正在尝试将列表中的项目重命名为

['person1','person2','person3']

谁能指导我。谢谢

【问题讨论】:

  • @khelwood 抱歉打错了,应该是 item3.. 已编辑列表

标签: python python-3.x list


【解决方案1】:

如果基本列表末尾只有一位数字,您可以使用:

>>> out = [] 
>>> input = ['item1','item2','item3']
>>> for i in input:
        out.append('person{}'.format(i[-1]))


>>> out
['person1', 'person2', 'person3']

编辑:

我也遇到过这个解决方案,它也适用于大于 9 的数字:

>>> items = ['item1', 'item2', 'item3']
>>> out = []

>>> for item in items:
        out.append('person{}'.format(int(filter(str.isdigit,item))))

>>> out
['person1', 'person2', 'person3']

【讨论】:

  • 感谢您的回复。我有一个包含 20 列的列表,每次列表都可以包含任意组合的列。
【解决方案2】:

考虑到速度和很多元素:

%%timeit
arr = ['item1', 'item2', 'item3']
arr = np.char.replace(arr, 'item', 'person')

每个循环 16.4 µs ± 1.07 µs(7 次运行的平均值 ± 标准偏差,每次 100000 次循环)

%%timeit
arr = ['item1', 'item2', 'item3']
arr = [x.replace('item', 'person') for x in arr]

每个循环 1.42 µs ± 174 ns(平均值 ± 标准偏差,7 次运行,每次 1000000 次循环)

即使是 100.000 个元素,使用 numpy 似乎也比较慢:

Numpy:每个循环 177 毫秒 ± 15.4 毫秒(平均值 ± 标准偏差,7 次运行,每次 1 个循环)

ListComprehension:每个循环 35.7 毫秒 ± 3.15 毫秒(平均值 ± 标准偏差,7 次运行,每次 10 次循环)

即使是 Pandas.Series 在我的测试中也比较慢:

%%timeit
series.str.replace('item', 'person')

每个循环 144 毫秒 ± 4.47 毫秒(平均值 ± 标准偏差,7 次运行,每次 10 次循环)

【讨论】:

    【解决方案3】:

    如果您想用特定值替换特定元素,请执行以下操作:

    In [521]: items = ['item1','item2','item3']
    
    In [522]: dic = {'item1':'person1', 'item2':'human', 'item3':'person3'}
    
    In [523]: [dic.get(n, n) for n in items]
    Out[523]: ['person1', 'human', 'person3']
    

    【讨论】:

      【解决方案4】:

      您可以使用replace"item" 更改为"person",并且您可以使用list comprehension 生成一个新列表。

      items = ['item1','item2','item3']
      people = [item.replace('item', 'person') for item in items]
      

      结果:

      ['person1', 'person2', 'person3']
      

      【讨论】:

      • 感谢您的回复。我可以再问一次编辑吗?如果我想将 item1 重命名为 person 并将 item2 重命名为 human 怎么办?我怎么能修改你的回复..谢谢
      猜你喜欢
      • 2021-04-17
      • 2018-11-16
      • 2018-03-04
      • 2021-06-09
      • 2018-05-08
      • 2017-04-29
      • 2021-04-07
      • 1970-01-01
      相关资源
      最近更新 更多