【问题标题】:Could someone explain why python dictionary is behaving in this manner? [duplicate]有人可以解释为什么python字典会以这种方式表现吗? [复制]
【发布时间】:2017-08-16 17:11:53
【问题描述】:

我正在尝试根据一组逻辑条件创建一个目录,但它只能通过第二个逻辑语句正确执行。

# Sample code:

test_dict = {}

file_0 = "C:/Year/yea_84.txt"
file_1 = "C:/Year/yea_92.txt"
file_2 = "C:/Year/yea_01.txt"
file_3 = "C:/Year/yea_06.txt"

for x in range(1985, 2008):
    if (x <= 1991):
        test_dict[x] = file_0
    elif (x > 1991 & x <= 2000):
        test_dict[x] = file_1
    elif (x > 2000 & x <= 2005):
        test_dict[x] = file_2
    elif (x > 2005):
        test_dict[x] = file_3

print test_dict

# Print result
1985 C:/Year/yea_84.txt
1986 C:/Year/yea_84.txt
1987 C:/Year/yea_84.txt
1988 C:/Year/yea_84.txt
1989 C:/Year/yea_84.txt
1990 C:/Year/yea_84.txt
1991 C:/Year/yea_84.txt
1992 C:/Year/yea_92.txt
1993 C:/Year/yea_92.txt
1994 C:/Year/yea_92.txt
1995 C:/Year/yea_92.txt
1996 C:/Year/yea_92.txt
1997 C:/Year/yea_92.txt
1998 C:/Year/yea_92.txt
1999 C:/Year/yea_92.txt
2000 C:/Year/yea_92.txt
2001 C:/Year/yea_92.txt
2002 C:/Year/yea_92.txt
2003 C:/Year/yea_92.txt
2004 C:/Year/yea_92.txt
2005 C:/Year/yea_92.txt
2006 C:/Year/yea_92.txt
2007 C:/Year/yea_92.txt

我怀疑这是因为每个循环字典都会打乱顺序,但这似乎是一个糟糕的解释。有人可以扩展这种行为吗?

【问题讨论】:

    标签: python python-2.7 dictionary


    【解决方案1】:

    您在进行布尔测试时使用了错误的运算符。 &amp;binary bitwise operator,而不是 boolean logic operator。因为它有一个different operator precedence,所以你真的在计算别的东西:

    x > 1991 & x <= 2000
    

    被解释为

    x > (1991 & x) <= 2000
    

    在你的 16 年里,这将是真的,包括 2001 年到 2007 年。

    改用and

    x > 1991 and x <= 2000
    

    或使用比较链:

    1991 < x <= 2000
    

    放在一起,将最后一个测试简化为else

    for x in range(1985, 2008):
        if x <= 1991:
            test_dict[x] = file_0
        elif 1991 < x <= 2000:
            test_dict[x] = file_1
        elif 2000 < x <= 2005:
            test_dict[x] = file_2
        else:
            test_dict[x] = file_3
    

    【讨论】:

    • 感谢您详细说明比较链!
    猜你喜欢
    • 2013-11-30
    • 2019-12-06
    • 1970-01-01
    • 2019-10-28
    • 2019-06-02
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2015-05-12
    相关资源
    最近更新 更多