[英]Comparing string objects within a list - Python
message = ["TS", "EE", "RE", "Z"]
So I'm trying to compare the characters within this list, and have conditions when some things arise such as if a value in the list for example "EE" is the same, it will return true and append a "Q" to separate the letters so the list looks like this 因此,我试图比较此列表中的字符,并在出现某些情况时设置条件,例如,如果列表中的值例如“ EE”相同,则它将返回true并附加“ Q”以分隔字母,所以列表看起来像这样
message = ["TS", "EQ", "ER" "EZ"]
So I tried it normally without looping it works but when I loop it says string index out of range. 因此,我通常在没有循环的情况下尝试了它,但是当我循环时说字符串索引超出范围。
a = ''
a = message[1]
if a[0] == a[1]:
print("True")
else:
print("False")
When looping 循环时
for i in range(len(message)):
a = ''
a = message[i]
if a[0] == a[1]:
print("True")
What should I do? 我该怎么办? Turn it into a string first and work on it? 首先将其转换为字符串并进行处理?
Note that there is an element "Z" in the array (ie message[-1]) that has only one char in it. 注意,数组中只有一个字符的元素“ Z”(即message [-1])。
def getIndex(message):
for i in range(len(message)):
a = message[i]
if a[0] == a[1]:
return i
index = getIndex(message)
tmp = message[index][1]
message[index][1] = 'Q'
for x in range(index+1, len(message)):
tmp1 = message[x][0]
if len(message[x])==1:
message[x][0] = tmp
message[x][1] = tmp1
return
else:
message[x][0] = tmp
tmp = message[x][1]
message[x][1] = tmp1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.