私信  •  关注

John Gordon

John Gordon 最近回复了
3 年前
回复了 John Gordon 创建的主题 » python中列表追加的差异

res.append(path) 附加实际的 path 对象,而不是它的副本。所以如果 路径 更改之后,更改将显示在 res 而且

res.append(list(path)) 附加一份副本。

3 年前
回复了 John Gordon 创建的主题 » 嵌套式If可选Python

您可以将范围保存在列表中,而不是有许多单独的变量:

ranges = [
    range(1,10),
    range(12,16),
    range(18,29),
    ...
]

然后你可以反复浏览列表:

for pos, r in enumerate(ranges):
    if level_buy in r:
        level = ranges[pos+1][0]

如果你不想要最后一个 a 范围链到第一个 b 范围,你也许可以保留两个列表。

5 年前
回复了 John Gordon 创建的主题 » 这个Python代码是做什么的?括号说明
a,b = something

这意味着 something 是两个值的序列。 a 分配给第一个值,并且 b 分配给第二个。

这叫做 元组解包 .

5 年前
回复了 John Gordon 创建的主题 » 如何在python中设置if语句以使用条件数组作为输入

制作 condition 始终是一个列表,即使它只有一个项目:

if test1.lower() == "keyword":
    condition = [password]
else:
    condition = [password1, password2, password3]

然后使用 all() 函数检查中的所有元素 条件 出现在F:

if all(c in f for c in condition):
    print("problem solved")

这将起作用 条件 有一个元素,或者十个,或者一百个。

6 年前
回复了 John Gordon 创建的主题 » 函数内部的python readline()跳过文件中的第二行

for line in filename: 读取文件中的每一行。

打电话 readline() 而在这样的循环中,正如您在第一个代码示例中所做的,将导致 for 循环以错过该行,因为它被 RealLoad() 不再可以被 对于 循环。

第二个代码示例没有这个问题,因为您不再调用 小精灵 里面 for line in file: 循环。

6 年前
回复了 John Gordon 创建的主题 » 在python中循环函数

对于第一个问题,可以重试多次。保留一个错误计数器,包装整个 try/except 在一个循环中,当您得到一个异常时,检查错误计数器,如果它小于(比如)5,则继续循环,否则会像您已经做的那样引发错误。

error_count = 0
while True:
    try:
        if cat is False:
            child.expect('.#')
            child.sendline('sh mac address-table | no-more')
        else:
            child.sendline('sh mac address-table dynamic | i Gi')
        child.expect('.#', timeout=3000)
        break
    except pexpect.TIMEOUT:
        ++error_count
        if error_count < 5:
            continue
        print child.before,child.after
        child.close()
        raise

对于第二个问题,是的,如果设备出现故障,只需将 return None 在“例外处理”中。但您还需要调整调用代码以正确处理 None 结果。

6 年前
回复了 John Gordon 创建的主题 » 在python中为对象中的多个变量赋值

减少代码重复的一种方法是定义属性名列表并使用 setattr() 分配它们:

for attribute in ['health', 'strength', 'defence', 'luck']:
    if points > 0:
        amount = int(input('Type in your %s: ' % attribute))
        setattr(optio, attribute, amount)
        points = points - amount
    else:
        print('No points left for %s' % attribute)
6 年前
回复了 John Gordon 创建的主题 » 在python中枚举和打印行。

第一个循环将排出文件中的所有行。当第二个循环尝试运行时,没有更多的行可读取,循环立即退出。

如果希望第一个循环在找到匹配行时停止,并允许第二个循环读取其余行,则可以添加 break 声明 if .

start_pattern = 'hello there'
end_pattern = 'goodblye now'
print_flag = False

with open('somefile.txt') as file:
    for line in file:
        if start_pattern in line:
            print_flag = True

        if print_flag:
            print line

        if end_pattern in line:
            break