Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/331.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

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/apache-flex/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 - Fatal编程技术网

如何在python中比较空列表和字符串列表?

如何在python中比较空列表和字符串列表?,python,Python,我有两个列表,data1和data2: data1 = [('hello world', [])] data2 = [('hello world', 'greetings')] 我想比较每个列表第二个位置的值 我使用下面的代码来比较它们,但它只打印“a等于c”,而不是“b等于d”,并且它打印以下结果: “值a:你好世界,值b:[],值c:你好世界,值d:你好” …它只打印a等于c,而不打印b等于d 1-b是d仅执行如果a是c是true,则需要修复缩进 2-is如果两个变量指向同一个对象,将返

我有两个列表,
data1
data2

data1 = [('hello world', [])]

data2 = [('hello world', 'greetings')]
我想比较每个列表第二个位置的值

我使用下面的代码来比较它们,但它只打印“a等于c”,而不是“b等于d”,并且它打印以下结果:

“值a:你好世界,值b:[],值c:你好世界,值d:你好”

…它只打印
a等于c
,而不打印
b等于d

1-
b是d
仅执行如果
a是c
true
,则需要修复缩进

2-
is
如果两个变量指向同一个对象,将返回
True
,如果变量引用的对象相等,则返回
=


你可能会得到这样的结果:

for a, b in data1:
    for c, d in data2:
        print("Value_a: %s, Value_b: %s,Value_c: %s,Value_d: %s," % (a, b, c, d))
        if a == c:
            print("a is equal to c")
        if b == d:
            print("b is equal to d")
            count += 1
            print("Count = ", count)

注:


您的示例应该适用,但要成对比较较长的列表

for (a,b),(c,d) in zip(data1,data2):

    print("Value_a: %s, Value_b: %s,Value_c: %s,Value_d: %s,"%(a,b,c,d))
    if a is c:
        print("a is equal to c")
        if b is d:
            print("b is equal to d")
            count+= 1
            print("Count = ",count)

也许你需要读一下:


此外,数据2包含两个字符串,而数据1包含一个字符串和一个空列表。

为什么它会打印“b等于d”?空列表以何种方式等于字符串<代码>“问候语”?同样,列表中的元组中有字符串。
data1
的第一个元素是
('hello world',[])
,没有第二个元素。请检查缩进<代码>b是d仅当
a是c时才会触发,这也是因为缩进您已经在准确比较第二个位置的值,因为
[]!='问候语“
。你能澄清你需要知道什么吗?如果b是d,程序会抛出
NamError
,因为
count
没有声明。用“==”代替“is”不是更好吗?你评论时我正在更新答案。不管怎样。
for (a,b),(c,d) in zip(data1,data2):

    print("Value_a: %s, Value_b: %s,Value_c: %s,Value_d: %s,"%(a,b,c,d))
    if a is c:
        print("a is equal to c")
        if b is d:
            print("b is equal to d")
            count+= 1
            print("Count = ",count)