简体   繁体   English

如何将列表(非2D)顺时针旋转90度?

[英]How to rotate a list(not 2D) 90 degree clockwise?

As a beginner in Python, I think the biggest problem I have is overcomplicating a problem when it can be done a lot simpler. 作为Python的初学者,我认为我遇到的最大问题是使问题变得更加简单,而这可以简化很多事情。 I have not found a solution for a list that is not two-dimensional, hence why I chose to ask. 我没有找到非二维列表的解决方案,因此为什么选择询问。

Here is an example of what I am trying to do: 这是我要执行的操作的一个示例:

# Before
alphabet = ["ABCDEFG",
            "HIJKLMN",
            "OPQRSTU"]
# After
rotated_alphabet = ["OHA",
                    "PIB",
                    "QJC",
                    "RKD",
                    "SLE",
                    "TMF",
                    "UNG"]     

What I have done so far: 到目前为止,我所做的是:

length_of_column = len(alphabet)
length_of_row = len(alphabet[0])
temp_list = []

x = -1
for i in range(length_of_column):
    while x < length_of_row-1:
        x += 1
        for row in alphabet:
            temp_list.append(row[x])

temp_list = temp_list[::-1]

Output 产量

print(temp_list)
>>> ['U', 'N', 'G', 'T', 'M', 'F', 'S','L','E','R','K','D','Q','J','C','P','I','B', 'O', 'H', 'A']

I need to make the list above in the desired format. 我需要以所需的格式制作上面的列表。

-How would I do this? 我该怎么办?

-Is there a simpler way to do it? -有更简单的方法吗?

You can just zip the list of strings, and it will make tuples character by character, then you'll only have to join the tuples in reverse order. 您只需zip字符串列表,它就会一个字符一个字符地组成元组,然后只需要以相反的顺序加入元组。 Here it is in just one line: 这里仅一行:

rotated_alphabet = [''.join(list(i)[::-1]) for i in zip(*alphabet)]

A variant of @MuhammadAhmad answer will be to use reversed , as reversed works with iterables, no need to convert to a list. @MuhammadAhmad答案的一个变体是使用reversed ,因为reversed可与可迭代对象一起使用,而无需转换为列表。

alphabet = ["ABCDEFG",
            "HIJKLMN",
            "OPQRSTU"]

rotated = [''.join(reversed(a)) for a in zip(*alphabet)]
print(rotated)

Output 产量

['OHA', 'PIB', 'QJC', 'RKD', 'SLE', 'TMF', 'UNG']

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

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