Python:用括号比较和替换列表[i]

标签 python string list replace

给定两个列表,我想比较 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)

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

感谢您的帮助!

最佳答案

这就是你在低级语言中会做的事情。除非您对此有特殊需要,否则在 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 是否包含某些内容,而list 的相同操作所花费的时间与其大小成比例。

关于Python:用括号比较和替换列表[i],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56748220/

相关文章:

python - 如何将列表列表转换为每个列表换行且没有逗号的字符串

android - Kotlin 在字符串列表中查找子字符串

python - 为什么 Python 的列表列表根据它们的声明表现不同?

python - 如何在 Pandas 的列中删除不包含字符串类型的行?

python - 我如何在 Django 中查询这个?

python - 如何更改子图中线条的颜色?

python - 为什么来自 s3 的 dask read_csv 保留了这么多内存?

Java 相当于 php pack ('H*' , str)

python - Unicode解码错误: 'ascii' codec can't decode byte 0xaa in position 2370: ordinal not in range(128)

c - 链表元素不见了?