繁体   English   中英

通过两个列表进行交互以获取 python 中的元组中的元素

[英]interate through two list to get elements in a tuple in python

我需要遍历两个句子列表(前提和假设)以获得前提和假设的元组。

到目前为止我所做的如下:

def examples (premises, hypotheses, labels):
    labels = list(labels)

    ls=[]


   for pr, hy in zip(premises, hypotheses):
      prs=tuple(pr, hy)
      ls=ls.append(prs)

我需要附加到列表的元组中的成对前提和假设。 我的代码有意义吗?

你可以使用这样的东西:

def examples (premises, hypotheses, labels):
    labels = list(labels)

    ls=[]


    for i in range(len(premises)):
        tupl = (premises[i], hypotheses[i])
        ls.append(tupl)

也不要使用ls=ls.append(Something) the.append 不返回任何内容,它只是修改列表。 像这样使用它ls.append(Something)

您的代码有一些可纠正的问题: 1. 您没有返回 ls; 2. .append 方法改变了 ls 所以你不应该说 ls = ls.append(); 3. 当您通过 zip object 使用两个变量进行迭代时,您会自动获得一个元组,因此您不想将其转换为元组。 最后,我不确定你想用标签做什么。 您的代码的正确版本是:

def examples (premises, hypotheses, labels):
    labels = list(labels)
    ls=[]
    for pr, hy in zip(premises, hypotheses):
      prs = pr, hy
      ls.append(prs)
    return ls

更优雅的方法是使用list comprehension

def f(premises, hypotheses):
    return [(p, h) for p, h in zip(premises, hypotheses)]

p = ["a", "b", "c", "d"]
h = ["1", "2", "3", "4"]

print("This is output of my function:", f(p, h))

Output:

This is output of my function: [('a', '1'), ('b', '2'), ('c', '3'), ('d', '4')]

暂无
暂无

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

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