python 获取列表中的每个奇数变量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1780763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Getting every odd variable in a list?
提问by John
If I make a list in Python and want to write a function that would return only odd numbers from a range 1 to x how would I do that?
如果我在 Python 中创建一个列表并想编写一个只返回 1 到 x 范围内的奇数的函数,我该怎么做?
For example, if I have list [1, 2, 3, 4] from 1 to 4 (4 ix my x), I want to return [1, 3].
例如,如果我有从 1 到 4 的列表 [1, 2, 3, 4] (4 ix my x),我想返回 [1, 3]。
回答by Alex Martelli
If you want to start with an arbitrary list:
如果要从任意列表开始:
[item for item in yourlist if item % 2]
but if you're always starting with range
, range(1, x, 2)
is better!-)
但如果你总是从range
,开始,range(1, x, 2)
那就更好了!-)
For example:
例如:
$ python -mtimeit -s'x=99' 'filter(lambda(t): t % 2 == 1, range(1, x))'
10000 loops, best of 3: 38.5 usec per loop
$ python -mtimeit -s'x=99' 'range(1, x, 2)'
1000000 loops, best of 3: 1.38 usec per loop
so the right approach is about 28 times(!) faster than a somewhat-typical wrong one, in this case.
所以在这种情况下,正确的方法比有点典型的错误方法快大约28 倍(!)。
The "more general than you need if that's all you need" solution:
“如果这就是你所需要的,那么比你需要的更通用”解决方案:
$ python -mtimeit -s'yourlist=range(1,99)' '[item for item in yourlist if item % 2]'
10000 loops, best of 3: 21.6 usec per loop
is only about twice as fast as the sample wrong one, but still over 15 times slower than the "just right" one!-)
仅比样本错误的快两倍,但仍比“恰到好处”的慢 15 倍以上!-)
回答by Jim Dennis
What's wrong with:
有什么问题:
def getodds(lst):
return lst[1::2]
....???
……???
(Assuming you want every other element from some arbitrary sequence ... all those which have odd indexes).
(假设您想要某个任意序列中的所有其他元素……所有具有奇数索引的元素)。
Alternatively if you want all items from a list of numbers where the value of that element is odd:
或者,如果您想要该元素值为奇数的数字列表中的所有项目:
def oddonly(lst):
return [x for x in lst if x % 2]
[Update: 2017]
[更新:2017]
You could use "lazy evaluation" to yield these from generators:
您可以使用“懒惰评估”从生成器中产生这些:
def get_elements_at_odd_indices(sequence):
for index, item in enumerate(sequence):
if index % 2:
yield item
else:
continue
For getting odd elements (rather than elements at each odd offset from the start of the sequence) you could use the even simpler:
要获取奇数元素(而不是从序列开始的每个奇数偏移处的元素),您可以使用更简单的方法:
def get_odd_elements(sequence):
for item in sequence:
if item % 2:
yield item
else:
continue
This should work for any sequence or iterable object types. (Obviously the latter only works for those sequences or iterables which yield numbers ... or other types for which % 2evaluates to a meaningfully "odd" result).
这应该适用于任何序列或可迭代对象类型。(显然,后者仅适用于产生数字的那些序列或可迭代对象......或其他类型,其中% 2评估为有意义的“奇数”结果)。
Also note that, if we want to efficiently operate on Pandasseries or dataframe columns, or the underlying NumPythen we could get the elements at odd indexes using the [1::2] slice notation, and we can get each of the elements containing odd values using NumPy's "fancy indexing"
另请注意,如果我们想对Pandas系列或数据帧列或底层NumPy进行有效操作,那么我们可以使用 [1::2] 切片符号获取奇数索引处的元素,并且我们可以获得包含使用 NumPy 的“花式索引”的奇数值
For example:
例如:
import numpy as nd
arr = nd.arange(1000)
odds = arr[arr%2!=0]
I show the "fancy index" as arr[arr%2!=0]because that will generalize better to filtering out every third, fourth or other nth element; but you can use much more elaborate expressions.
我将“花式索引”显示为arr[arr%2!=0]因为这将更好地概括为过滤掉每三个、第四个或其他第 n 个元素;但是您可以使用更复杂的表达式。
Note that the syntax arr[arr%2!=0]may look a bit odd. It's magic in the way that NumPy over-rides various arithmetic and bitwise operators and augmented assignment operations. The point is that NumPy evaluates such operations into machine code which can be efficiently vectorized over NumPy arrays ... using SIMDwherever the underlying CPU supports. For example on typical laptop and desktop systems today NumPy can evaluate many arithmetic operations into SSEoperations.
请注意,语法arr[arr%2!=0]可能看起来有点奇怪。NumPy 覆盖各种算术和位运算符以及增强赋值运算的方式很神奇。关键是 NumPy 将这些操作评估为机器代码,这些机器代码可以在 NumPy 数组上有效地向量化......在底层 CPU 支持的任何地方使用SIMD。例如,在当今典型的笔记本电脑和台式机系统上,NumPy 可以将许多算术运算计算为SSE运算。
回答by tzot
To have a range of odd/even numbers up to and possibly including a number n, you can:
要获得一系列奇数/偶数直至并可能包括数字 n,您可以:
def odd_numbers(n):
return range(1, n+1, 2)
def even_numbers(n):
return range(0, n+1, 2)
If you want a generic algorithm that will take the items with odd indexesfrom a sequence, you can do the following:
如果您想要一个从序列中获取具有奇数索引的项目的通用算法,您可以执行以下操作:
import itertools
def odd_indexes(sequence):
return itertools.islice(sequence, 1, None, 2)
def even_indexes(sequence):
return itertools.islice(sequence, 0, None, 2)