【问题标题】:Python replace list elements in 2 lists, at indexes of substrings in 3rd listPython 替换 2 个列表中的列表元素,位于第 3 个列表中的子字符串索引处
【发布时间】:2017-06-12 09:07:52
【问题描述】:

我有以下 3 个 Python 列表:

cl_ambient = ['BRy', 'WilmB', 'Hgan', 'FoVx', 'Afree', 'FoVx_d', 'Afree_d']
temp_farh = ['grey', 'DarkOrange', 'r', 'black', 'black', 'black', 'black']
manual_calib = ['white', 'white', 'white', 'blue', 'yellow', 'green', 'darkgreen']

所有 3 个列表的长度始终相同。

从列表开始cl_ambient

我需要在cl_ambient 中找到元素的索引,这是另一个元素的子字符串。在这种情况下, 这些元素的索引位于索引 3,5 (Fovx,Fovx_d) 和 4,6 (Afree,Afree_d)。

现在,一旦找到这些索引,我需要使用这些索引在其他两个列表中进行替换:

我需要用较低的索引元素替换其他 2 个列表(temp_farhmanual_calib)中较高的索引元素 来自manual_calib 列表。因此,如果我们手动执行此操作,则替换应该是:

temp_farh[5] = temp_farh[3]
temp_farh[6] = temp_farh[4]

manual_calib[5] = temp_farh[3]
manual_calib[6] = temp_farh[4]

我需要以编程方式进行这些替换。我无法手动执行此操作,因为列表可能很长。

所需输出:

输出应该是:

cl_ambient = ['BRy', 'WilmB', 'Hgan', 'FoVx', 'Afree', 'FoVx_d', 'Afree_d']
temp_farh = ['grey', 'DarkOrange', 'r', 'black', 'black', 'blue', 'yellow']
manual_calib = ['white', 'white', 'white', 'blue', 'yellow', 'blue', 'yellow']

问题:

有没有办法以编程方式从这 3 个列表中提取这些子字符串元素?

其他信息:

  1. 根据下面的评论,我将添加以下内容:cl_ambient 列表中不会存在超过 2 个子字符串的情况。示例:FoVxFoVx_dFoVx_a 将不存在。只有Fovx_dFovx_a
  2. 子字符串将始终位于 cl_ambient 列表中较长的元素之前。

【问题讨论】:

  • 如果cl_ambient 中有两个以上的子字符串怎么办。示例:FoVxFoVx_dFoVx_a 那么会发生什么?
  • 感谢您的来信。这种情况在cl_ambient 列表中是不可能的。我会将这个添加到 OP 中,好问题。
  • 子字符串总是在较长的元素之前吗?
  • 抱歉耽搁了。我应该在 OP 中提到这一点。是的!子字符串总是在较长的元素之前。

标签: python list indexing replace slice


【解决方案1】:

答案分为两部分,首先找到我们要替换的所需索引然后进行替换

代码:

cl_ambient = ['BRy', 'WilmB', 'Hgan', 'FoVx', 'Afree', 'FoVx_d', 'Afree_d']
temp_farh = ['grey', 'DarkOrange', 'r', 'black', 'black', 'black', 'black']
manual_calib = ['white', 'white', 'white', 'blue', 'yellow', 'green', 'darkgreen']


# for each index search match on the higher indexes, 
# if found save it on the changes list as (high, low) tuple
changes = [(i+1+j, i) for i, s1 in enumerate(cl_ambient)
           for j, s2 in enumerate(cl_ambient[i+1:]) 
           if (s1 in s2 or s2 in s1)]
print(changes)

# do the change on both lists
for i, j in changes:
    temp_farh[i] = manual_calib[j]
    manual_calib[i] = manual_calib[j]

print(temp_farh)
print(manual_calib)

输出:

[(5, 3), (6, 4)]
['grey', 'DarkOrange', 'r', 'black', 'black', 'blue', 'yellow']
['white', 'white', 'white', 'blue', 'yellow', 'blue', 'yellow']

【讨论】:

  • 谢谢。您的 manual_calib 效果很好。但是,对于temp_farh 列表,我需要最后两个元素为blue,'yellow'。
  • 哦等等。抱歉,如果您只进行一项更改,它就可以工作。将for 循环中的第一行更改为:temp_farh[i] = manual_calib[j]
猜你喜欢
  • 1970-01-01
  • 2020-01-10
  • 2021-09-26
  • 1970-01-01
  • 2021-02-23
  • 2019-08-03
  • 2019-02-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多