我想比较两个字符串列表,分别是textsplited和column1。你知道吗
目前我正在两个列表中循环,如果它们不相同,第2列和第3列中应该有一个连字符(-)。如果它们相同,则第2列和第3列的值应保持在该位置。你知道吗
注1:第1列、第2列和第3列最初的长度相同。你知道吗
注2:column1永远不会包含textSplitted没有的元素。你知道吗
textSplitted = ['wow','this','is','some','nice','text']
column1 = ['this','is','some','text']
column2 = ['A','B','C','D']
column3 = ['Q1','Q2','Q3','Q4',]
i = 0
j = 0
for item in textSplitted:
if textSplitted[i] == column1[j]:
i+=1
j+=1
elif textSplitted[i] != column1[j]:
column2.insert(j,"-")
column3.insert(j,"-")
i+=1
print(textSplitted)
print(column2)
print(column3)
这将产生输出:
['wow', 'this', 'is', 'some', 'nice', 'text']
['-', 'A', 'B', '-', 'C', 'D']
['-', 'Q1', 'Q2', '-', 'Q3', 'Q4']
但我想实现:
['wow', 'this', 'is', 'some', 'nice', 'text']
['-', 'A', 'B', 'C', '-', 'D']
['-', 'Q1', 'Q2', 'Q3', '-', 'Q4']
注意:如果我想在textSplitted中添加一个额外的元素,输出将产生:列表索引超出范围错误。但是,如果column1“超出”比较范围,则textSplitted中的剩余元素应在column2和column3中获得相应的连字符(-)。例如:
['wow', 'this', 'is', 'some', 'nice', 'text','yes','indeed']
['-', 'A', 'B', 'C', '-', 'D','-','-']
['-', 'Q1', 'Q2', 'Q3', '-', 'Q4','-','-']
你必须在索引x处进行替换
这应该做到:
印刷品:
这可能是一个要求,也可能不是,但是如果column1中的元素在textSplitted中出现多次,那么发布的解决方案(当我发布它们时,可能它们现在已更新)将失败,例如:
下面修复了该潜在问题:
相关问题 更多 >
编程相关推荐