简体   繁体   English

回文检查器:列表索引混乱,这是如何工作的?

[英]Palindrome checker: list indexing confusion, how is this working?

I was trying to make a program that takes a string as an input and checks whether it is a palindrome.我试图制作一个将字符串作为输入并检查它是否是回文的程序。 I wrote this and it works but I'm confused as to how it works.我写了这个并且它有效,但我对它是如何工作的感到困惑。 Specifically, the list indexing when making the reverse list.具体来说,制作反向列表时的列表索引。 Could someone please explain this step wise, I've been trying to follow it.有人可以明智地解释这一步,我一直在努力遵循它。 Now I'm wondering how I even wrote this then.现在我想知道我当时是怎么写的。

word = input("Enter a word. ")
letter_list = []

for i in word:
    letter_list.append(i)
print(letter_list)
reverse = []
len = len(letter_list)

for i in letter_list:
    reverse.insert(-(len - 1), i)
print(reverse)

if letter_list == reverse:
    print("This word is a palindrome.")
else:
    print("This word is not a palindrome.")

I was trying to make a program that takes a string as an input and checks whether it is a palindrome.我试图制作一个将字符串作为输入并检查它是否是回文的程序。

If you want to check if a word is palindrome you can do it in a very simple way:如果你想检查一个单词是否是回文,你可以用一个非常简单的方法来做:

>>> def is_palindrome(word):
...     return word == word[::-1]
...
>>> word = input("Enter a word: ")
Enter a word: kajak
>>> word
kajak
>>> is_palindrome(word)
True
>>>

word[::-1] returns word string in reverse. word[::-1]反向返回word字符串。

But if you want to make it as for loop in a list of chars, then here is a code:但是,如果您想在字符列表中使其成为 for 循环,那么这里有一段代码:

def is_palindrome(letters):
    l = len(letters)
    for i, letter in enumerate(letters):
        if letters[i] != letters[l-1 - i]:
            return False
    return True

letter_list = list(input("Enter a word: "))
print(is_palindrome(letter_list))

Result:结果:

Enter a word: kajak
True

I recommend you first method.我推荐你第一种方法。 It's much faster它快得多

Edit - Explanation编辑 - 解释

for i in word:
        letter_list.append(i)

letter_list is filled with every letter that user typed, eg for "kajak" is ['k', 'a', 'j', 'a', 'k'] . letter_list填充了用户输入的每个字母,例如“kajak”是['k', 'a', 'j', 'a', 'k']

for i in letter_list:
    reverse.insert(-(len - 1), i)
print(reverse)

Insert every letter from letter_list to reverse at index -(len - 1) .插入letter_list中的每个字母以在索引处reverse -(len - 1)

if letter_list == reverse:
    print("This word is a palindrome.")
else:
    print("This word is not a palindrome.")

If lists are equal then print that word is palindrome.如果列表相等,则打印该单词是回文。 Else not.否则没有。

NOTE: * You loop with reverse is wrong.注意: * 你用reverse循环是错误的。 You are constantly inserting a letter to the same position, which makes other words shift.你不断地向同一个 position 插入一个字母,这使得其他词发生了变化。 It works, but it's not good.它有效,但它并不好。 Also try not to name your variables with keywords ( len is built-in function. You should do something as letters_len = len(letter_list) )也尽量不要用关键字命名你的变量( len是内置的 function。你应该做一些事情作为letters_len = len(letter_list)

The insert command receives an index and an element to be inserted. insert 命令接收要插入的索引和元素。 The elements are shifted to the right in order to store the new element.元素向右移动以存储新元素。 Since the command由于命令

reverse.insert(-(len - 1), i)

in your code is always inserting the element i at the beginning of the new list (- (len - 1) (insertion of negative indexes goes through the end to the beginning), and i is varying from the beginning to the end of the original list letter_list ,在您的代码中始终在新列表的开头插入元素i (- (len - 1) (负索引的插入从结尾到开头),并且i从原始列表的开头到结尾都在变化列出letter_list

for i in letter_list:

then the new list will contain the original reversed.那么新列表将包含原来的反转。 Then you just compare to see whether they are equal.然后你只需比较一下它们是否相等。

letter_list == reverse

By the way, the command reverse.insert(-(len - 1), i) has the same effect as顺便说一句,命令reverse.insert(-(len - 1), i)具有相同的效果

reverse.insert(0, i)

You could use this site in order to follow the execution step by step.您可以使用此站点来逐步执行操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM