【问题标题】:Combined update and replacement in a list列表中的组合更新和替换
【发布时间】:2018-02-17 04:27:57
【问题描述】:

所以我有两个列表。一个包含所有类别,另一个只有需要审核的类别。

List_one = ('Maths', 'English', 'Science')

List_two = ('Maths:2', 'Science:4')

我想要一份完整的清单,如下所示:

List_three = ('Maths:2', 'English', 'Science:4')

任何帮助将不胜感激!

【问题讨论】:

  • 你确定这些列表不应该是像{'Maths': 2, 'Science': 4} 这样的字典吗?这可能会更容易处理。
  • 那些不是列表,那些是tuples
  • 我正在读取 grep -r -c -i string *.txt 的终端输出。每一行输出变成一个变量

标签: python list for-loop replace


【解决方案1】:

您可以通过创建中间dict 来提高性能,以便在执行替换时执行恒定时间查找。

dict_two = {x.split(':')[0] : x for x in List_two}

out = [dict_two.get(x, x) for x in List_one]
print(out) 
['Maths:2', 'English', 'Science:4']

使用dict.get,您可以替换列表元素并同时避免KeyErrors,时间复杂度为O(n)

【讨论】:

    【解决方案2】:

    Coldspeed 指出了最高效的方法。天真的方法是

    List_one = ('Maths', 'English', 'Science')
    
    List_two = ('Maths:2', 'Science:4')
    
    list_three  = tuple(x for x in List_one if not any(y.split(":")[0]==x for y in List_two)) + List_two
    

    删除列表一中与列表二匹配的项目,然后添加列表二。但是由于隐含的any 循环,性能很差。

    【讨论】:

      【解决方案3】:
      List_one = ('Maths', 'English', 'Science')
      List_two = ('Maths:2', 'Science:4')
      import copy
      List_temp = list(copy.copy(List_one)) #Creating a copy of your original list
      

      List_temp 的输出:

      ['数学'、'英语'、'科学']

      #Iterate through each element of List_temp and compare the strings with each element of List_two
      
      #Have used python's inbuilt substring operator to compare the lists
      
      for i in List_temp:
      List_three = []
      for j in range(len(List_two)):
          if str(i) in str(List_two[j]):
              y = i
              List_temp.remove(y) #Remove the elements present in List_two
      List_three = List_two + tuple(List_temp) #Since we cant merge a tuple and list, have converted List_temp to tuple and added them to create a new tuple called List_three
      print(List_three)
      

      代码输出:

      ('数学:2','科学:4','英语')

      希望对你有帮助

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-05
        • 2019-04-10
        • 2023-04-01
        • 1970-01-01
        • 2016-03-17
        • 1970-01-01
        • 1970-01-01
        • 2021-11-12
        相关资源
        最近更新 更多