这个 (if char_set[val]:) 语句在 python 中是什么意思?

问题描述

这是我试图更好地理解的代码

def is_unique_chars_algorithmic(string):
    # Assuming character set is ASCII (128 characters)
    if len(string) > 128:
        return False

    # this is a pythonic and faster way to initialize an array with a fixed value.
    #  careful though it won't work for a doubly nested array
    char_set = [False] * 128
    for char in string:
        val = ord(char)
        if char_set[val]: # From here I am unable to understand
            # Char already found in string
            return False
        char_set[val] = True

    return True

请帮助我更好地理解这个程序!

编辑:- 终于理解了代码 :) 将该行写为 (If char_set[val]==True: ) 对我来说似乎更清楚!

解决方法

if char_set[val]

这会查找您的列表是否在索引 val 处包含真值。除非您在此索引处为 None 或 False,否则它将返回 True。

给定这段代码,逻辑就行了。 读取unicode代码字符点:

val = ord(char)

使用以下方法检查字符是否已存在于 char_set 中:

 if char_set[val]

如果以上陈述为真。我们没有一串唯一的字符,返回 False 否则在 char_set 中的 val 处存储“True”:

char_set[val] = True