如何在python 3中获取子数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38049214/
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
How to obtain a subarray in python 3
提问by Rohith
I want to get a subarray in python 3. I have tried the following.
我想在 python 3 中获得一个子数组。我尝试了以下方法。
a = ['abcdefgh', 'abcdefgh' , 'abcdefgh']
print (a[0][3:6])
print (a[1][2:6])
print (a[0:2][3:6])
I get the first two results as expected. But I am not able to obtain the desired result for the 3rd print statement.
我得到了预期的前两个结果。但是我无法获得第三个打印语句的预期结果。
Output :
输出 :
def
cdef
[]
Desired Output :
期望输出:
def
cdef
['def', 'def']
Can anyone tell me how to obtain it
谁能告诉我怎么获得
回答by Sardorbek Imomaliev
Use list comprehension for this
为此使用列表理解
print ([i[3:6] for i in a[0:2]])
回答by Abdul Fatir
This will work. It will iterate over elements at index 0 and 1 and will slice the array as expected.
这将起作用。它将迭代索引 0 和 1 处的元素,并按预期对数组进行切片。
[x[3:6] for x in a[0:2]]