我如何将其转换为Python代码?

R. *_*ing -1 python loops

x = [1, 3, 2, 5, 7]
Run Code Online (Sandbox Code Playgroud)

从列表的第一个值开始:

如果下一个值更大,则打印 "\nthe value x is greater than y"

如果下一个值相等,则打印 "\nthe value x is equal to y"

如果下一个值较小,则打印 "\nthe value x is smaller than y"

如何将其转换为精确的Python代码?我实际上正在使用pandas数据框,我只是通过使用列表作为示例来简化它.

x = [1, 3, 2, 5, 7]
Run Code Online (Sandbox Code Playgroud)

根据上面给出的,输出应该是这样的:

the value 3 is greater than 1
the value 2 is smaller than 3
the value 5 is greater than 2
the value 7 is greater than 5
Run Code Online (Sandbox Code Playgroud)

Jea*_*bre 6

直接生成输出使用str.join和列表理解使用自身的移位版本压缩列表,以便在理解内部进行比较:

x = [1, 3, 2, 5, 7]

output = "\n".join(["the value {} is {} than {}".format(b,"greater" if b > a else "smaller",a) for a,b in zip(x,x[1:])])

print(output)
Run Code Online (Sandbox Code Playgroud)

(请注意,"大于"或"小于"并不严格,即使令人困惑也适用于相等的值,因此可能会创建第三种替代方案来处理Benedict建议的情况,如果情况可能发生)

结果:

the value 3 is greater than 1
the value 2 is smaller than 3
the value 5 is greater than 2
the value 7 is greater than 5
Run Code Online (Sandbox Code Playgroud)

你可以用这些变种摆弄线条:

"".join(["the value {} is {} than {}\n" ...
Run Code Online (Sandbox Code Playgroud)

要么

"".join(["\nthe value {} is {} than {}" ...
Run Code Online (Sandbox Code Playgroud)