从python列表中提取一系列数据
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19521032/
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
Extracting a range of data from a python list
提问by Fisher
I have a list of unicode values. To the best of my knowledge I can use list[starting location:length to select] to select a range of values from a list, right?
我有一个 unicode 值列表。据我所知,我可以使用 list[starting location:length to select] 从列表中选择一系列值,对吗?
I have a list of 78 unicode values, which are not all unique. When I select a range of 5 values beginning from the 0 position in the list (example: list[0:5]) the correct values are returned. However, when I try to select a range of values that do not begin at the 0 position in the list (example: list[44:5]) then the return is []. Changing the length of the range does not seem to make any difference. Furthermore, if I use list[44], for example, then the value that is returned is correct.
我有一个包含 78 个 unicode 值的列表,这些值并非都是唯一的。当我选择从列表中的 0 位置开始的 5 个值范围(例如:list[0:5])时,将返回正确的值。但是,当我尝试选择不在列表中的 0 位置开始的值范围(例如:list[44:5])时,返回值为 []。改变范围的长度似乎没有任何区别。此外,例如,如果我使用 list[44],则返回的值是正确的。
I do not understand why I cannot select from a list when the cursor is not located at 0. Can anyone tell me if lists in python have limitations on how data can be retrieved as a range? I hope my problem and question are clear enough. I would appreciate any feedback. Thanks.
我不明白为什么当光标不在 0 时我不能从列表中选择。谁能告诉我 python 中的列表对如何将数据作为范围检索有限制?我希望我的问题和问题足够清楚。我将不胜感激任何反馈。谢谢。
采纳答案by CT Zhu
You should do list[44:49]
rather than list[44:5]
.
Usually when you want to fetch 5 items after (including) the a+1th item, you do L[a, a+5]
.
'Usually' implies there are more flexible ways to do so: see Extended Slices: http://docs.python.org/release/2.3/whatsnew/section-slices.html.
你应该做list[44:49]
而不是list[44:5]
. 通常,当您想在(包括)第 a+1 个项目之后获取 5 个项目时,您可以执行L[a, a+5]
. “通常”意味着有更灵活的方法可以这样做:请参阅扩展切片:http: //docs.python.org/release/2.3/whatsnew/section-slices.html。
Also try not to use list
as your list name. It overwrites list()
.
也尽量不要list
用作您的列表名称。它覆盖list()
.
回答by Inbar Rose
It is list[starting:ending] notlist[starting:length].
它是列表[开始:结束]而不是列表[开始:长度]。
So you should do list[44:49]
所以你应该做 list[44:49]
For more information on slice notation click here
回答by falsetru
In the slice notation [a:b]
, the second value (b
) is not length, but a upper bound.
在切片表示法中[a:b]
,第二个值 ( b
) 不是长度,而是一个上限。
To get five elements starting from 44
you should use [44:49]
(49 = 44 + 5)
要从44
你开始得到五个元素,你应该使用[44:49]
(49 = 44 + 5)
If upper bound is smaller than lower bound, you get empty sequence.
如果上限小于下限,则会得到空序列。