【问题标题】:Comparing two tuples from different lists比较来自不同列表的两个元组
【发布时间】:2013-05-17 14:51:03
【问题描述】:

我有这个基本代码,我只是想将第一个列表 (list1) 中的每个元组与第二个列表 (list 2) 中的相应元组进行比较。如果列表 2 中的元组是 = 到列表 1 中的相应元组减去 '.vbproj',则获取两个元组并返回它们。

然后我需要打印路径 + 来自 list2 的元组 + 来自 list1 的元组。我只是被困在如何做到这一点。

path = "C:\Users\bg\Documents\Brent"

list1 = [ 'Brent.vbproj', 'Chris.vbproj', 'Nate.vbproj']
list2 = ['Brent', 'Chris', 'Nate']

def connect(list1, list2):

    for x, y in zip(string[0], string2[0]):
        if string(x) is string2(y):
            print x
            os.path.join(path, x, y)




x = connect(list1, list2)
y = connect(list1, list2)

我认为zip() 比较了两个元组的最小等价,但我可能是错的??我不知道,任何帮助将不胜感激。提前致谢!

【问题讨论】:

  • 退货后打印的目的是什么?
  • 您的意思是用list1list2 打电话给connect 吗?
  • @oleg 我只是想看看它是否正常工作
  • 我认为你应该使用 os.path.join(path, x, y) 而不是 path + "\\" + x + "\\" + y
  • 在这个例子中,函数中返回后的代码永远不会运行

标签: python list tuples


【解决方案1】:

使用== 来测试是否相等。 is 测试身份,两侧是同一个对象。此外,您的输入 stringstring2 不是函数,因此您不能调用它们。直接比较xy即可:

if x == y:

请注意,当您调用return 时,函数结束。下一行的print 语句被忽略,for 循环也结束。

最后但同样重要的是,您只是压缩stringstring2first 元素。我怀疑你想用list1list2 来调用它,此时你可能想先配对'Brent.vbproj''Brent',然后是'Chris.vbproj''Chris',等等。如果是这样,就通过没有索引的列表

for x, y in zip(string, string2):

我怀疑你会实现你想要的; list1list2 中的任何值对都不会相等。

也许你想看看str.startswith() method?此外,os.path library 具有您想要熟悉的功能,如果您正在操作和测试文件名和路径。 os.path.join()os.path.splitext()os.path.commonprefix() 函数应该对我认为你在这里尝试做的事情特别感兴趣。

请注意,您的 path 变量也需要调整。使用原始字符串、正斜杠或双斜杠:

path = r"C:\Users\bg\Documents\Brent"
path = "C:\\Users\\bg\\Documents\\Brent"
path = "C:/Users/bg/Documents/Brent"

\b 是退格的转义码。

【讨论】:

  • @martijin 我将is 更改为== 仍然不起作用,现在它说`无法调用列表对象` 谢谢你的路径建议,我会的以后一定要留意!
  • @Martijin 所以如果我传入两个列表而不添加索引,它只会逐个元组地通过它?
  • @bbesase:完全正确;如果您将两个 字符串 配对,它们将通过字符对来遍历它们:zip('aa', 'bb') 变为 [('a', 'b'), ('a', 'b')]
  • @martijin 太棒了!它现在运行,我只需要对输出格式做一些工作!非常感谢你们
【解决方案2】:

你还没有定义stringstring2!!无论如何,我从您的问题文本中理解了您的问题!

比较list1 中的元组与list2 中的对应 元组,我自己作为初学者会以另一种方式进行..

>>> path = r"C:\Users\bg\Documents\Brent"
>>> list1 = [ 'Brent.vbproj', 'Chris.vbproj', 'Nate.vbproj']
>>> list2 = ['Brent', 'Chris', 'Nate']
>>> for i in range(0, len(list1)):
    if i < len(list2):
        if list2[i][:] == list1[i][:len(list2[i])]:
            print(path + list2[i] + list1[i]) #Print syntax is for python 3


C:\Users\bg\Documents\BrentBrentBrent.vbproj
C:\Users\bg\Documents\BrentChrisChris.vbproj
C:\Users\bg\Documents\BrentNateNate.vbproj
>>> 

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-22
    • 2017-09-01
    • 1970-01-01
    • 2019-03-08
    • 2020-02-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多