在Python中交换字符串列表中的字符
给出字符串列表,例如:在Python中交换字符串列表中的字符,python,string,list,Python,String,List,给出字符串列表,例如:[“数学很酷”,“鸡蛋和培根”] 如何将单词从一个列表项交换到另一个列表项以将它们转换为类似的内容 [“培根很酷”,“鸡蛋和数学”] 我会张贴代码,如果我有,但我真的不知道从哪里开始这个。谢谢 我正在使用Python 3 import random def swap_words(s1, s2): s1 = s1.split() # split string into words s2 = s2.split() w1 = random.rand
[“数学很酷”,“鸡蛋和培根”]
如何将单词从一个列表项交换到另一个列表项以将它们转换为类似的内容
[“培根很酷”,“鸡蛋和数学”]
我会张贴代码,如果我有,但我真的不知道从哪里开始这个。谢谢
我正在使用Python 3
import random
def swap_words(s1, s2):
s1 = s1.split() # split string into words
s2 = s2.split()
w1 = random.randrange(len(s1)) # decide which words to swap
w2 = random.randrange(len(s2))
s1[w1], s2[w2] = s2[w2], s1[w1] # do swap
return " ".join(s1), " ".join(s2)
然后swap_单词('Math is cool','egs and bacon')
返回如下句子
('Math and cool', 'eggs is bacon')
('bacon is cool', 'eggs and Math')
从创建列表开始
text1 = 'Math is cool'
text2 = 'eggs and bacon'
mylist = []
mylist.append(text1.split())
mylist.append(text2.split()
print mylist
输出:
[['Math', 'is', 'cool'], ['eggs', 'and', 'bacon']]
现在你有了列表,就可以玩了。使用append()添加用户输入的文本等
我想你可以从这里看到下一步的方向。你没有提供太多关于你总体目标的信息(至少可以说)。。。因此,以下答案仅指问题中给出的具体示例,以帮助您开始:
list = ['Math is cool', 'eggs and bacon']
list0 = list[0].split(' ')
list1 = list[1].split(' ')
newList = [list1[-1]+' '+' '.join(list0[1:]), ' '.join(list1[:-1])+' '+list0[0]]
你有交换单词的计划吗?例如,始终将第一个字符串的第一个单词与第二个字符串的最后一个单词交换。我希望用户能够输入列表项(即1-n)和列表中他们希望与相应列表项和单词交换的单词。谢谢,您使用的是什么版本的Python?(
2.x
或3.x
)我能够使用string.strip去掉单词,但我不知道如何用正确的方式替换它们position@user2913067请发布尝试此操作的代码。OP要求用户输入交换,而不是随机交换。本示例中显示了重要的函数调用