python列表输出奇数位素颜引对应的元素,在奇数位置提取列表元素

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.

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.):

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. Usually it is in the following form:

some_list[start:stop:step]

If we omitted start, the default (0) would be used. So the first element (at position 0, because the indexes are 0-based) would be selected. 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. 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:

take the second element (which, by the way, is an odd element, if you judge from the index),

skip one element (because we have step=2, so we are skipping one, as a contrary to step=1 which is default),

take the next element,

Repeat steps 2.-3. until the end of the list is reached,

EDIT: @PreetKukreti gave a link for another explanation on Python's list slicing notation. See here: Explain Python's slice notation

Extras - replacing counter with 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():

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值