简体   繁体   English

Python:迭代列表列表中的列以查找回文

[英]Python: Iterating through the columns in a list of list to find the palindromes

Here I have a word list as: 这里我有一个单词列表:

[['r', 'o', 't', 'o', 'r'], ['e', 'v', 'e', 'i', 'a'], ['f', 'i', 'n', 'e', 'd'], ['e', 'n', 'e', 't', 'a'], ['r', 'a', 't', 'e', 'r']]

And I have to display all the palindromes in this list which are in rows as well as columns. 而且我必须显示此列表中的所有回文项,包括行和列。 I have coded to find all the palindromes in the rows. 我编码找到行中的所有回文。 But cannot implement a method to find the palindromes in the columns. 但无法实现一种方法来查找列中的回文。

Here is my code so far: 到目前为止,这是我的代码:

result_1=""
if len(palindrome)==len_line_str:
    for row in range(len(palindrome)):
        for horizontal_line in range(len(palindrome[row])):
            if ''.join(palindrome[row])==''.join(reversed(palindrome[row])):
                result_1=''.join(palindrome[row])+" is a palindrome starting at ["+str(row)+"]["+str(row)+"] and is a row in the table"
    print(result_1)

Which will display the output: 这将显示输出:

rotor is a palindrome starting at [0][0] and is a row in the table

Where "rotor" is a palindrome. “转子”是回文的地方。

I need a method to get the palindromes in the columns which are: "refer", "tenet", "radar" 我需要一种方法来获得列中的回文:“引用”,“原则”,“雷达”

Any help is much appreciated. 任何帮助深表感谢。 Thanks in advance! 提前致谢!

You can use zip to transpose your lists: 您可以使用zip来转置列表:

>>> t = [['r', 'o', 't', 'o', 'r'], ['e', 'v', 'e', 'i', 'a'], ['f', 'i', 'n', 'e', 'd'], ['e', 'n', 'e', 't', 'a'], ['r', 'a', 't', 'e', 'r']]
[['r', 'o', 't', 'o', 'r'], ['e', 'v', 'e', 'i', 'a'], ['f', 'i', 'n', 'e', 'd'], ['e', 'n', 'e', 't', 'a'], ['r', 'a', 't', 'e', 'r']]
>>> list(zip(*t))
[('r', 'e', 'f', 'e', 'r'), ('o', 'v', 'i', 'n', 'a'), ('t', 'e', 'n', 'e', 't'), ('o', 'i', 'e', 't', 'e'), ('r', 'a', 'd', 'a', 'r')]

Your columns are now rows, and you can apply the same method than before. 您的列现在是行,您可以应用与以前相同的方法。 If you just need the words, you can use list comprehensions: 如果您只需要单词,可以使用列表推导:

>>> rows = [['r', 'o', 't', 'o', 'r'], ['e', 'v', 'e', 'i', 'a'], ['f', 'i', 'n', 'e', 'd'], ['e', 'n', 'e', 't', 'a'], ['r', 'a', 't', 'e', 'r']]
>>> [''.join(row) for row in rows if row[::-1] == row ]
['rotor']
>>> [''.join(column) for column in zip(*rows) if column[::-1] == column ]
['refer', 'tenet', 'radar']

This will do the job: 这将完成工作:

palindrome=[['r', 'o', 't', 'o', 'r'], ['e', 'v', 'e', 'i', 'a'], ['f', 'i', 'n', 'e', 'd'], ['e', 'n', 'e', 't', 'a'], ['r', 'a', 't', 'e', 'r']]
n=len(palindrome)
for col in range(len(palindrome[0])):
    col_word=[palindrome[i][col] for i in range(n)]
    if ''.join(col_word)==''.join(reversed(col_word)):
        result=''.join(col_word)+" is a palindrome starting at ["+str(col)+"] and is a col in the table"
        print(result)

This prints 这打印

refer is a palindrome starting at [0] and is a col in the table
tenet is a palindrome starting at [2] and is a col in the table
radar is a palindrome starting at [4] and is a col in the table

Basically, in order to access the words in the column, you can do 基本上,为了访问列中的单词,您可以这样做

col_word=[palindrome[i][col] for i in range(n)] 

This fixes the column and iterates over the rows. 这将修复列并迭代行。 The rest of the code is structures similarly to yours. 代码的其余部分与您的结构类似。

I saw you did not want to use Zip (which I would recommend using): 我看到你不想使用Zip(我建议使用):

Alternative answer: 替代答案:

list_ = [['r', 'o', 't', 'o', 'r'], ['e', 'v', 'e', 'i', 'a'], ['f', 'i', 'n', 'e', 'd'], ['e', 'n', 'e', 't', 'a'], ['r', 'a', 't', 'e', 'r']]

You can get the palindromes (rows) by checking each list with the reversed list [::-1]: 您可以通过使用反向列表[:: - 1]检查每个列表来获取回文(行):

[i==i[::-1] for i in list_]
# prints [True, False, False, False, False]

And get the palindromes (columns) by 1. create the column list (called list_2 below) with a list comprehension and 2. same principle as above: 并通过1创建回文(列)。使用列表推导创建列列表(下面称为list_2)和2.与上面相同的原则:

list_2 = [[i[ind] for i in list_] for ind in range(len(list_))]
[i==i[::-1] for i in list_2]
# prints [True, False, True, False, True]

Update 更新

If you want the answers directly you can do: 如果你想直接得到答案,你可以这样做:

[i for i in list_ if i==i[::-1]] 
# prints [['r', 'o', 't', 'o', 'r']]
# and list_2: [['r', 'e', 'f', 'e', 'r'],['t', 'e', 'n', 'e', 't'],['r', 'a', 'd', 'a', 'r']]

There are a lot of ways to do it. 有很多方法可以做到这一点。 I will take as example your code because of your effort on it 我将以您的努力为例,将您的代码作为示例

Another alternative following your code, is creating the columns in another list and check wich of them are palindromes: 代码之后的另一个替代方法是在另一个列表中创建列并检查它们是否是回文:

palindrome = [['r', 'o', 't', 'o', 'r'], 
              ['e', 'v', 'e', 'i', 'a'], 
              ['f', 'i', 'n', 'e', 'd'], 
              ['e', 'n', 'e', 't', 'a'], 
              ['r', 'a', 't', 'e', 'r']]

len_line_str = 5

result_1=""

def is_pal(string):
  return string == reversed(string)

colums = []
if len(palindrome)==len_line_str:
  for row in range(len(palindrome)):
    vertical = []
    if ''.join(palindrome[row])==''.join(reversed(palindrome[row])):
      result_1+=''.join(palindrome[row])+" is a palindrome starting at ["+str(0)+"]["+str(row)+"] and is a row in the table. " + "\n"
    for horizontal_line in range(len(palindrome[row])):
      if(len_line_str-1 > horizontal_line): 
        vertical += [palindrome[horizontal_line][row]]
      else:
        vertical += [palindrome[horizontal_line][row]]
        colums += [(vertical,row)]

  for word in colums:
    if ''.join(word[0])==''.join(reversed(word[0])):
        result_1+=''.join(word[0])+" is a palindrome starting at ["+str(0)+"]["+str(word[1])+"] and is a column in the table" + "\n"
  print(result_1)

This should work. 这应该工作。 First loop iterates through the list s and the second loop iterates through each list. 第一个循环遍历列表s,第二个循环遍历每个列表。

Assuming s is the name of the list- [['r', 'o', 't', 'o', 'r'], ['e', 'v', 'e', 'i', 'a'], ['f', 'i', 'n', 'e', 'd'], ['e', 'n', 'e', 't', 'a'], ['r', 'a', 't', 'e', 'r']] 假设s是列表的名称 - [['r','o','t','o','r'],['e','v','e','i',' a'],['f','i','n','e','d'],['e','n','e','t','a'],[' r','a','t','e','r']]

for i in xrange(0,len(s),1):
    str = ""
    for j in s:
        str = str + j[i]
    print str
    if str == str[::-1]:
        print str," is a pallindrome - column", i
    else:
        print str," is not a pallindrome - column", i

There is no column wise traversal in Python. Python中没有列式遍历。 One hacky way you can follow is to perform transpose operation on your input matrix. 您可以遵循的一种hacky方式是在输入矩阵上执行转置操作。 Below is a simple way to implement transpose using list comprehensions. 下面是使用列表推导实现转置的简单方法。

def transpose(matrix):
    if not matrix:
        return []
    return [[row[i] for row in matrix] for i in range(len(matrix[0]))]

Your same logic should work once modify your input using transpose. 使用转置修改输入后,相同的逻辑应该有效。

Hope this helps!! 希望这可以帮助!!

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

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