【问题标题】:Python: comparing and replacing list[i] with bracketsPython:用括号比较和替换 list[i]
【发布时间】:2019-11-06 22:45:30
【问题描述】:

给定两个列表,我想比较 list1 和 list2,并在 list1 中替换它,并添加括号。

str1 = "red man juice"
str2 = "the red man drank the juice"

one_lst = ['red','man','juice']
lst1 = ['the','red','man','drank','the','juice']

预期输出:

lst1 = ['the','[red]','[man]','drank','the','[juice]']

到目前为止我尝试了什么:

lst1 = list(str1.split())
for i in range(0,len(lst1)):
    for j in range(0,len(one_lst)):
        if one_lst[j] == lst1[i]:
            str1 = str1.replace(lst1[i],'{}').format(*one_lst)
lst1 = list(str1.split())
print(lst1)

我可以替换它,但只是没有括号。

感谢您的帮助!

【问题讨论】:

  • 您需要检查订单吗?如果str1"man juice red",结果会是什么?
  • 它将始终按时间顺序通过主通道。

标签: python string list replace


【解决方案1】:

这就是你在低级语言中会做的事情。除非您对此有特殊需要,否则在 Python 中,我会改为使用 list 理解:

str1 = 'red man juice'
str2 = 'the red man drank the juice'

words_to_enclose = set(str1.split())

result = [f'[{word}]'  # replace with '[{}]'.format(word) for Python <= 3.5
          if word in words_to_enclose 
          else word 
          for word in str2.split()]

print(result)

输出:

['the', '[red]', '[man]', 'drank', 'the', '[juice]']

转换为set 的好处是检查set 是否包含某些内容(无论它有多大)都需要(大致)相同的时间,而@987654326 进行相同操作所需的时间@ 随其大小缩放。

【讨论】:

  • 我只想补充一点,f-strings 是 Python 3.6+。 OP 可能不是最新的。否则,+1
【解决方案2】:
str1 = 'red man juice'
str2 = 'the red man drank the juice'

one_lst = ['red','man','juice']
lst1 = ['the','red','man','drank','the','juice']

res=[]

for i in lst1:
    if i in one_lst:
        res.append('{}{}{}'.format('[',i,']'))
    else:
        res.append(i)

print(res)

输出

['the', '[red]', '[man]', 'drank', 'the', '[juice]']

【讨论】:

  • 为什么不'[{}]'
  • @gmds 它可以使用,提到的方式首先想到所以我写了它
  • 嘿,这个解决方案有效,但我得到这个输出:['t','h',' ','[','r','e','d' ,']',' '等...
  • @swamz 你能提供意见吗?
【解决方案3】:

这是一个单行建议:

[x if x not in str1.split(' ') else [x] for x in str2.split(' ')]

输出

['the', ['red'], ['man'], 'drank', 'the', ['juice']]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-26
    • 2019-02-03
    • 1970-01-01
    • 2021-12-26
    • 1970-01-01
    • 1970-01-01
    • 2017-03-14
    • 1970-01-01
    相关资源
    最近更新 更多