简体   繁体   English

在奇数位置提取列表元素

[英]Extract elements of list at odd positions

So I want to create a list which is a sublist of some existing list.所以我想创建一个列表,它是某个现有列表的子列表。

For example,例如,

L = [1, 2, 3, 4, 5, 6, 7] , I want to create a sublist li such that li contains all the elements in L at odd positions. L = [1, 2, 3, 4, 5, 6, 7] ,我想创建一个子列表li使得li包含L中奇数位置的所有元素。

While I can do it by虽然我可以做到

L = [1, 2, 3, 4, 5, 6, 7]
li = []
count = 0
for i in L:
    if count % 2 == 1:
        li.append(i)
    count += 1

But I want to know if there is another way to do the same efficiently and in fewer number of steps.但我想知道是否有另一种方法可以有效地以更少的步骤完成同样的事情。

Solution解决方案

Yes, you can:是的你可以:

l = L[1::2]

And this is all.这就是全部。 The result will contain the elements placed on the following positions ( 0 -based, so first element is at position 0 , second at 1 etc.):结果将包含放置在以下位置的元素(基于0 ,因此第一个元素位于位置0 ,第二个元素位于1等):

1, 3, 5

so the result (actual numbers) will be:所以结果(实际数字)将是:

2, 4, 6

Explanation解释

The [1::2] at the end is just a notation for list slicing.最后的[1::2]只是列表切片的一种表示法。 Usually it is in the following form:通常它是以下形式:

some_list[start:stop:step]

If we omitted start , the default ( 0 ) would be used.如果我们省略start ,则将使用默认值 ( 0 )。 So the first element (at position 0 , because the indexes are 0 -based) would be selected.所以第一个元素(在位置0 ,因为索引是基于0的)将被选择。 In this case the second element will be selected.在这种情况下,将选择第二个元素。

Because the second element is omitted, the default is being used (the end of the list).因为省略了第二个元素,所以使用了默认值(列表的末尾)。 So the list is being iterated from the second element to the end .所以列表正在从第二个元素迭代到结尾

We also provided third argument ( step ) which is 2 .我们还提供了第三个参数( step ),即2 Which means that one element will be selected, the next will be skipped, and so on...这意味着将选择一个元素,将跳过下一个元素,依此类推...

So, to sum up, in this case [1::2] means:所以,总而言之,在这种情况下[1::2]意味着:

  1. take the second element (which, by the way, is an odd element, if you judge from the index),取第二个元素(顺便说一下,如果从索引判断,它是一个奇数元素),
  2. skip one element (because we have step=2 , so we are skipping one, as a contrary to step=1 which is default),跳过一个元素(因为我们有step=2 ,所以我们跳过了一个,与默认的step=1相反),
  3. take the next element,取下一个元素,
  4. Repeat steps 2.-3.重复步骤 2.-3。 until the end of the list is reached,直到到达列表的末尾,

EDIT : @PreetKukreti gave a link for another explanation on Python's list slicing notation.编辑:@PreetKukreti 提供了有关 Python 列表切片符号的另一种解释的链接。 See here: Explain Python's slice notation请参阅此处: 解释 Python 的切片符号

Extras - replacing counter with enumerate()附加 - 用enumerate()替换计数器

In your code, you explicitly create and increase the counter.在您的代码中,您显式地创建并增加了计数器。 In Python this is not necessary, as you can enumerate through some iterable using enumerate() :在 Python 中,这不是必需的,因为您可以使用enumerate()枚举一些可迭代对象:

for count, i in enumerate(L):
    if count % 2 == 1:
        l.append(i)

The above serves exactly the same purpose as the code you were using:以上与您使用的代码的用途完全相同:

count = 0
for i in L:
    if count % 2 == 1:
        l.append(i)
    count += 1

More on emulating for loops with counter in Python: Accessing the index in Python 'for' loops有关在 Python 中使用计数器模拟for循环的更多信息:访问 Python 'for' 循环中的索引

For the odd positions, you probably want:对于奇数位置,您可能想要:

>>>> list_ = list(range(10))
>>>> print list_[1::2]
[1, 3, 5, 7, 9]
>>>>

I like List comprehensions because of their Math (Set) syntax.我喜欢列表推导式,因为它们的数学(集合)语法。 So how about this:那么这个怎么样:

L = [1, 2, 3, 4, 5, 6, 7]
odd_numbers = [y for x,y in enumerate(L) if x%2 != 0]
even_numbers = [y for x,y in enumerate(L) if x%2 == 0]

Basically, if you enumerate over a list, you'll get the index x and the value y .基本上,如果您枚举列表,您将获得索引x和值y What I'm doing here is putting the value y into the output list (even or odd) and using the index x to find out if that point is odd ( x%2 != 0 ).我在这里做的是将值y放入输出列表(偶数或奇数)并使用索引x找出该点是否为奇数( x%2 != 0 )。

You can make use of bitwise AND operator & .您可以使用按位 AND 运算符& Let's see below:让我们看看下面:

x = [1, 2, 3, 4, 5, 6, 7]
y = [i for i in x if i&1]
>>> 
[1, 3, 5, 7]

Bitwise AND operator is used with 1, and the reason it works because, odd number when written in binary must have its first digit as 1. Let's check按位 AND 运算符与 1 一起使用,它起作用的原因是,用二进制编写的奇数必须将其第一位为 1。让我们检查一下

23 = 1 * (2**4) + 0 * (2**3) + 1 * (2**2) + 1 * (2**1) + 1 * (2**0) = 10111
14 = 1 * (2**3) + 1 * (2**2) + 1 * (2**1) + 0 * (2**0) = 1110

AND operation with 1 will only return 1 (1 in binary will also have last digit 1), iff the value is odd.与 1 的 AND 运算将仅返回 1(二进制中的 1 也将具有最后一位数字 1),如果该值是奇数。

Check the Python Bitwise Operator page for more.查看 Python按位运算符页面了解更多信息。

PS: You can tactically use this method if you want to select odd and even columns in a dataframe. PS:如果您想在数据框中选择奇数列和偶数列,您可以在战术上使用此方法。 Let's say x and y coordinates of facial key-points are given as columns x1, y1, x2, etc... To normalize the x and y coordinates with width and height values of each image you can simply perform假设面部关键点的 x 和 y 坐标以列 x1、y1、x2 等形式给出...要使用每个图像的宽度和高度值对 x 和 y 坐标进行归一化,您可以简单地执行

for i in range(df.shape[1]):
    if i&1:
        df.iloc[:, i] /= heights
    else:
        df.iloc[:, i] /= widths

This is not exactly related to the question but for data scientists and computer vision engineers this method could be useful.这与问题并不完全相关,但对于数据科学家和计算机视觉工程师来说,这种方法可能很有用。

Cheers!干杯!

list_ = list(range(9)) 打印(list_[1::2])

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

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