Python:在lis中交换两个字符串

2024-10-01 09:27:51 发布

您现在位置:Python中文网/ 问答频道 /正文

好的,所以我在将一个字符串的一部分与列表中另一个字符串的一部分交换时遇到了一个问题。我在这个网站上也看到过其他类似的问题,但似乎没有一个对我有用。在

假设我有一个列表:

sentList = ['i like math', 'i am a cs expert']

现在我想使用由用户输入确定的变量将“math”与“cs”切换。在

^{pr2}$

那么,现在我该如何交换这两个选项,以便我的列表返回以下内容:

sentList = ['i like cs', 'i am a math expert']

一如既往,谢谢你的帮助。我想我可以使用替换功能,但不确定如何使用。我想应该是这样的:

sentList = [sentListN.replace(currentWord, newWord) for sentListN in sentList]

但是,很明显这是行不通的。在


Tags: 字符串用户功能列表网站选项mathcs
3条回答

你可以通过简单的交换函数来实现。不需要使代码复杂化:)

def swap(str, x, y):
    words = []
    for w in str.split():
        if w == x:
            words.append(y)
        elif w == y:
            words.append(x)
        else:
            words.append(w)
    return ' '.join(words)

if __name__ == '__main__':
    sentList = ['i like math', 'i am a cs expert']
    word1 = 'math'
    word2 = 'cs'
    new_list = [swap(x, word1, word2) for x in sentList]
    print(new_list)

一个使用list comprehension的单行程序。在

[sent.replace(currentWord,newWord) if sent.find(currentWord)>=0 else sent.replace(newWord,currentWord) for sent in sentList]

所以

^{pr2}$

在这里,if sent.find('math')>=0将发现字符串是否包含'math',如果是,则将其替换为'cs',否则它将{}替换为'math'。如果字符串既不包含,也将打印原始字符串,因为只有找到子字符串时,replace才起作用。在


编辑:正如@Rawing指出的,上面的代码中有一些错误。所以这里有新的代码可以处理所有的情况。在

我已经使用re.sub来处理只有单词的替换,替换算法就是如何交换两个变量,比如x和{},其中我们引入一个临时变量t来帮助交换:t = x; x = y; y = t。选择这种方法是因为我们必须同时进行多次替换。在

from re import sub

for s in sentList:

  #replace 'math' with '%math_temp%' in s (here '%math_temp%' is a dummy placeholder that we need to later substitute with 'cs')
  temp1 = sub(r'\bmath\b','%math_temp%' , s)

  #replace 'cs' with 'math' in temp1
  temp2 = sub(r'\bcs\b','math', temp1)

  #replace '%math_temp%' with 'cs' in temp2
  s = sub('%math_temp%','cs', temp2)

  print(s)

所以这次在一个更大的测试用例中,我们得到:

IN : sentList = ['i like math', 'i am a cs expert', 'math cs', 'mathematics']
IN : currentWord = "math"
IN : newWord = "cs"

OUT : i like cs
      i am a math expert
      cs math
      mathematics

下面的代码可以工作。我使用word1(currentWord)和word2(newWord)变量作为用户输入

sentList = ['i like math', 'i am a cs expert']

word1 = 'math'
word2 = 'cs'

assert word1, word2 in sentList
sentList = [s.replace(word1, word2) if word1 in s
           else s.replace(word2, word1) if word2 in s
           else s for s in sentList]

如果我们把它分解成台阶,看起来像

^{pr2}$

相关问题 更多 >