简体   繁体   English

如何使用切片来反转列表?

[英]How to reverse a list using slicing?

Let's suppose I have a string text = "Hello". 假设我有一个字符串text =“ Hello”。 I want to print separately the odd/even positions of the string. 我想分别打印字符串的奇数/偶数位置。 I have managed to do this in normal order (see code below). 我设法按正常顺序执行此操作(请参见下面的代码)。

The problem now is that I want to do the same but starting from the end. 现在的问题是我想做同样的事情,但是要从头开始。 That is, odd now equals to "le" and even equals to "olH". 也就是说,奇数现在等于“ le”,甚至等于“ olH”。

    text = "Hello"

    # Normal order
    odd = text[1::2] # --> "el"
    even = text[0::2] # --> "Hlo"

    # Reverse order (WRONG)
    odd = text[-2::2] 
    even = text[-1::2]

You also need to negate the increment: 您还需要取反增量:

oddReverse = text[-2::-2]
evenReverse = text[-1::-2]

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

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