Python - 在两个字符串上运行

时间:2012-12-12 20:56:21

标签: python python-3.x python-2.7

我正在尝试在获取两个参数的函数上组合for循环。我需要运行两个参数(它们都是整数列表)。尝试这个并不适合我:

def xor_bytes (b, a):
    for i in range (b):
    for Z in range (a):
        if b[i]>a[Z]:
            return byte1
        if b[i]<a[Z]:
            return byte2
        if b[i]==a[Z]:
            return 0

1 个答案:

答案 0 :(得分:2)

def xor_bytes (b, a):
    for i,z in zip(b,a):
        if i>z:
            return byte1
        if i<z:
            return byte2
        if i==z:
            return 0
  1. 查看zip的标准库文档或在终端
  2. 上试用
  3. 案件问题。我修复了你的大写z s
  4. 没有必要使用范围迭代列表。只需遍历列表即可。
  5. 此代码实际上不会按预期工作,或者根本不会,因为您有未定义的变量
  6. 请注意,您的代码实际上只返回一个字节。您可能希望将其用作生成器:

    def xor_bytes (b, a):
        for i,z in zip(b,a):
            if i>z:
                yield i
            if i<z:
                yield z
            if i==z:
                yield chr(0)
    
    
    In [6]: list(xor_bytes('hambone', 'cheesey'))
    Out[6]: ['h', 'h', 'm', 'e', 's', 'n', 'y']
    

    你可能会想要这个:

    In [13]: [chr(ord(a)^ord(b)) for a,b in zip('hambone', 'cheesey')]
    Out[13]: ['\x0b', '\t', '\x08', '\x07', '\x1c', '\x0b', '\x1c']
    

    如果不明显,则需要两个字节的字符串并返回一个字节列表(或技术上,长度为1个字节的字符串),其中包含xoring每对字节的结果。

    可替换地:

    In [14]: ''.join(chr(ord(a)^ord(b)) for a,b in zip('hambone', 'cheesey'))
    Out[14]: '\x0b\t\x08\x07\x1c\x0b\x1c'