简体   繁体   English

列表中的嵌套元组

[英]Nested tuples within lists

I have a list of lists of tuples and am having trouble accessing the values within the tuples.我有一个元组列表列表,但无法访问元组中的值。

Note: apologies for the basic nature of this query, but I'm a beginner and it takes me a long time to access simple variables.注意:对此查询的基本性质表示歉意,但我是初学者,访问简单变量需要很长时间。

E.g: 

[[('foo', '-1')],[('bar', '-5'),('baz', '+7')], [('qux', '+9')]]

I want to 1) remove the second value of each tuple ie the numbers and 2) remove the tuple type and just convert it a list of strings.我想 1) 删除每个元组的第二个值,即数字和 2) 删除元组类型并将其转换为字符串列表。

As you can see, it is a list of tuples so it can be one tuple or a number of tuples based on the content of extraction - but it is always 2 values within each tuple and I want to remove the second value.如您所见,它是一个元组列表,因此它可以是一个元组或多个基于提取内容的元组 - 但它始终是每个元组中的 2 个值,我想删除第二个值。

I am having trouble 1) converting each tuple to a string, to be able to 2) remove the second value (preferably I want to remove that before making it into a string) - any ideas?我遇到了麻烦 1) 将每个元组转换为字符串,以便能够 2) 删除第二个值(最好是我想在将其转换为字符串之前删除它)-有什么想法吗?

I don't understand very well the question but two points:我不太明白这个问题,但有两点:

  1. Your values in tuple are already string.您在元组中的值已经是字符串。

  2. To access tuple, you can iterate over your list and access first value of tuple by doing this:要访问元组,您可以遍历列表并通过执行以下操作访问元组的第一个值:

tuple[0]

I don't understand if you have a list of list of tuple, or a list of tuple我不明白您是否有元组列表列表元组列表

Just get 0 index of each tuple by iterating in list通过在列表中迭代得到每个元组的 0 索引

ll_tuple = [[('foo', '-1')],[('bar', '-5'),('baz', '+7')], [('qux', '+9')]]
print(
    [
        [tuple_[0] for tuple_ in l_tuple]
        for l_tuple in ll_tuple
    ]
)

First of all your list of lists of tubles is incorrectly formatted I assume what you mean:首先,您的管列表列表格式不正确,我假设您的意思是:

data = [
    [('foo', '-1')],
    [('bar', '-5')],
    [('baz', '+7'), ('qux', '+9')]
]

When create a nested for loop and append the first element in each tuble to new list output.当创建一个嵌套的 for 循环和 append 时,每个小管中的第一个元素到新列表 output。

output = []
for lst in data:
   for tub in lst:
      output.append(tub[0])
print(output)

Prints:印刷:

['foo', 'bar', 'baz', 'qux']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM