【问题标题】:How do you rotate an array of strings in Python?如何在 Python 中旋转字符串数组?
【发布时间】:2018-07-17 09:56:41
【问题描述】:

在 Python 中,给定以下字符串数组,

[   'abc',
    'def',
    'ghi',
    'jkl'
]

你怎么把它变成这样的,

[   'jgda',
    'kheb',
    'lifc'
]

【问题讨论】:

    标签: python arrays string matrix


    【解决方案1】:

    使用zipstr.join

    例如:

    a = ['abc', 'def', 'ghi', 'jkl']
    
    for i in zip(*a):
        print("".join(i)[::-1])
    

    输出:

    jgda
    kheb
    lifc
    
    • [::-1] 反转字符串。

    【讨论】:

    • list(map(''.join, zip(*reversed(lst))))
    • @tobias_k 谢谢 :)
    • 是的,当然,颠倒列表 first 是一种改进,在你的语法中是 for i in zip(*a[::-1]): print("".join(i))
    【解决方案2】:

    你可以使用 numpy

    import numpy as np
    x = ['abc',
         'def',
         'ghi',
         'jkl'
      ]
    
    a = np.rot90([list(row) for row in x], 3)
    result = [''.join(row) for row in a]
    

    输出:

    [
     'jgda', 
     'kheb', 
     'lifc'
    ]
    

    【讨论】:

      猜你喜欢
      • 2018-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-21
      • 2017-02-19
      • 2020-01-23
      • 2014-10-23
      • 2020-10-27
      相关资源
      最近更新 更多