Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/list/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何从长度可变的元组列表中提取数据_Python_List_Tuples - Fatal编程技术网

Python 如何从长度可变的元组列表中提取数据

Python 如何从长度可变的元组列表中提取数据,python,list,tuples,Python,List,Tuples,我有一个包含多个元组的列表(项目的长度是可变的),我想提取一些位于元组中相同等级的特定数据 让我给你举个例子。让我们来研究这3个元组的列表: x = [ ('a1', 'b2', 'c3', 'd4'), ('e5', 'f6', 'g7', 'h8'), ('i9', 'j10', 'k11', 'l12') ] 我想检索每个元组的第四项。我在While循环中使用列表的长度: y = len(x) while y > 0: print(x[0][3]

我有一个包含多个元组的列表(项目的长度是可变的),我想提取一些位于元组中相同等级的特定数据

让我给你举个例子。让我们来研究这3个元组的列表:

x = [
    ('a1', 'b2', 'c3', 'd4'), 
    ('e5', 'f6', 'g7', 'h8'), 
    ('i9', 'j10', 'k11', 'l12')
]
我想检索每个元组的第四项。我在
While
循环中使用列表的长度:

y = len(x)
while y > 0:
    print(x[0][3])
    y = y - 1
我得到的结果是:

d4
d4
d4
但我希望得到以下结果:

d4
h8
l12
d4
h8
l12
是否有方法将
[0]
替换为本节
print(x[0][3])
中的y变量,以获得我想要的结果?

尝试以下方法:

[each_tuple[-1] for each_tuple in x]
您可以尝试以下方法:-

y = len(x)
while y>0:
    print(x[len(x)-y][3])
    y = y-1
输出:-


使用for循环更自然:

for item in x:
    print(item[3])
您的代码不起作用的原因是,您对其进行了硬编码,以始终获取列表中的第一个元组,即在
print(x[0][3])
中,
x[0]
中的
0
需要是一个在列表中迭代的变量。如果你向上计数而不是向下计数,这会更容易

counter = 0
while counter < len(x):
    print(x[counter][3])
    counter += 1
计数器=0
当计数器

但是,当存在
for
时,使用
而使用
是没有意义的。

只需简单地对它们进行迭代,一旦完成,就会得到如下所示的元组

('a1', 'b2', 'c3', 'd4')
('e5', 'f6', 'g7', 'h8') 
('i9', 'j10', 'k11', 'l12')
一旦你得到它们,在每个元组上建立索引,得到最后一个值,比如
[-1]
[len(tuples)-1]
以下是我的代码


x = [
    ('a1', 'b2', 'c3', 'd4'), 
    ('e5', 'f6', 'g7', 'h8'), 
    ('i9', 'j10', 'k11', 'l12')
]

read = [i[-1] for i in x]
print(read)
试试看 循环的
for循环

x = [
    ('a1', 'b2', 'c3', 'd4'), 
    ('e5', 'f6', 'g7', 'h8'), 
    ('i9', 'j10', 'k11', 'l12')
]

for y in x:
    print(y[3])
c = len(x)-1
while c>=0:
    print(x[c][-1])
    c-=1
    
While循环

x = [
    ('a1', 'b2', 'c3', 'd4'), 
    ('e5', 'f6', 'g7', 'h8'), 
    ('i9', 'j10', 'k11', 'l12')
]

for y in x:
    print(y[3])
c = len(x)-1
while c>=0:
    print(x[c][-1])
    c-=1
    

每次在循环中,您实际上都在打印
print(x[0][3])
这是一个常量值。是的
print(x[y][3])
print(x[y][3])
给了我这个索引器:列出了所有的索引range@FrançoiseDionisi这是因为
y
是倒数,你可以在y
从0开始时做
,但是for循环更有意义。是的。y开始是x的长度。Python使用0索引列表。范围中最大的索引是
len(x)-1
,但不要将
tuple
用作变量名:)是的,为变量指定类似的名称可能是一个坏习惯。但是在这里它应该可以正常工作。谢谢。简单:)这不会造成问题,但可能会导致一些非常奇怪的错误。你真的应该编辑答案并修改它。@Gad上面的代码有效。你为什么拒绝?拒绝是什么意思