【问题标题】:How do I translate this into Python code?如何将其翻译成 Python 代码?
【发布时间】:2017-11-04 17:57:06
【问题描述】:
x = [1, 3, 2, 5, 7]

从列表的第一个值开始:

如果下一个值更大,则打印"\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]

有了上面给出的,输出应该是这样的:

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

【问题讨论】:

  • 如果值相等怎么办?如果列表中的值少于两个怎么办?你试过什么代码,你卡在哪里了?示例输出中的最后一行不应该是the value 7 is greater than 5吗?
  • 我已经编辑了错别字,很抱歉。我对所有事情都束手无策,我试着自己思考并做,但我什至不知道从哪里开始。

标签: python loops


【解决方案1】:

另一个 Python 2 单行。这个处理相同的项目。

x = [1, 3, 2, 5, 5, 7]
print '\n'.join('the value %s is %s %s'%(u,['equal to','greater than','less than'][cmp(u,v)],v)for u,v in zip(x[1:],x))

输出

the value 3 is greater than 1
the value 2 is less than 3
the value 5 is greater than 2
the value 5 is equal to 5
the value 7 is greater than 5

可以通过将cmp 定义为:

cmp = lambda x,y : 0 if x==y else -1 if x < y else 1

【讨论】:

  • @PM2Ring 很好地使用了cmp,但这仅适用于python 2。但是您可以在python 3 中使用cmp = lambda x,y : 0 if x==y else -1 if x &lt; y else 1 模拟cmp。我不推荐仅使用python-2 的代码。
  • @Jean-FrançoisFabre 好吧,我确实说过这是 Python 2 的答案。这些天我通常不会只编写 Python 2 代码(除非问题是特定于 Python 2 的),我只是在玩一些“代码高尔夫”的乐趣。
  • @PM2Ring 我知道你知道 :) 我冒昧地编辑了你的答案以使其符合 python 3 我希望你不介意。
  • @Jean-FrançoisFabre 在这种情况下我不介意,尽管通常我更喜欢建议编辑的评论,尤其是当答案仍然新鲜时。 FWIW,我几乎自己添加了一个 cmp 定义,但我想保持代码最少,本着代码高尔夫的精神。
  • 我同意它很难缩短。不过,您可以删除print 和引号之间的空格:)
【解决方案2】:

使用 lambda 函数的示例

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

greater = lambda a, b: a > b

old_i = x[0]
for i in x[1::]:
    if old_i :
        print(i,"is", 
              "greater" if greater(i, old_i) else "smaller","than",old_i)
    old_i = i

输出

3 is greater than 1
2 is smaller than 3
5 is greater than 2
7 is greater than 5

【讨论】:

  • 如果列表中只有 2 个元素,这将失败
  • @gipsy 它不会,它会循环一次并退出。对于x=[1,3],它将打印3 is greater than 1。是什么让你认为它会失败?
  • @sylvain1811 在您编辑之前是这样。 gist.github.com/gipsy86147/0db105070aa188a8b9c873f5f7613598
  • @gipsy 是的,我忘记将变量 previous_i 重构为 old_i。这不是列表大小问题。
  • 是的,你是对的。但是对于大小大于 2 的列表,该错误代码可以正常工作。这就是我想指出这一点的原因。
【解决方案3】:

使用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)

(请注意,“大于”或“小于”并不严格,即使令人困惑,也适用于相等的值,因此如果可能发生这种情况,也许可以创建第三种替代方案来处理 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

您可以使用这些变体来调整换行符:

"".join(["the value {} is {} than {}\n" ...

"".join(["\nthe value {} is {} than {}" ...

【讨论】:

  • 谢谢你!感谢您花时间回答和解释! :D
【解决方案4】:

使用递归:

def foo(n, remaining):
  if not remaining:
    return
  if n < remaining[0]:
    print('the value {} is greater than {}'.format(remaining[0], n))
  else:
    print('the value {} is smaller than {}'.format(remaining[0], n))
  foo(remaining[0], remaining[1:])


def the_driver(num_list):
  foo(num_list[0], num_list[1:])


if __name__ == '___main__':
  x = [1, 3, 2, 5, 7]
  the_driver(x)

【讨论】:

    【解决方案5】:

    Python 2 单线:

    [print(str(l[i+1])+" is greater than" + str(l[i])) if l[i+1]>l[i] else print(str(l[i+1])+" is smaller than" + str(l[i])) for i in range(len(l)-1)]
    

    【讨论】:

    • 是python中三元运算符的基本用法。您也只能批准一个答案;)(正如您尝试为所有人做的那样)
    • 哈哈哈!是的,对不起!我想我会批准一个得票最多的,因为它也帮助了其他人。
    • 要添加“等于”,请检查此答案:stackoverflow.com/questions/9987483/…
    【解决方案6】:
    x = [1,4,5,3,4]
    
    for i in range(0, len(x) - 1):
        out = "is equal to"
        if (x[i] < x[i + 1]):
            out = "is greater than"
        elif (x[i] > x[i + 1]):
            out = "is less than"
    
        print ("%s %s %s" % (x[i + 1], out, x[i]))
    

    你也想要解释吗?

    编辑: 糟糕,它会输出:
    4 大于 1
    5 大于 4
    3 小于 5
    4 大于 3

    【讨论】:

    • 好的,这很简单。 (对不起,不小心按了 Enter!)
    • 我们定义 x 我们使用 range 遍历列表,range 类似于 for 循环,将从起点 y 迭代 x 次作为输出 i(有关 range 的更多帮助,请参见链接)。默认情况下,我们设置为“等于”,因为如果条件不小于或大于等于,则它必须等于。然后实际上我们要检查的是数组中的 i 索引是否小于/大于下一个索引!然后以正确的格式输出。如果您不熟悉 python 中的数组,i-programmer.info/programming/python/3942-arrays-in-python.html,最好在那里学习。 (也进入范围)
    • 哦,另外,使用了字符串格式 "%s %s %s" % (x[i + 1], out, x[i]) (python从c偷来的)用于快速格式化。在最基本的层面上, "%s world" % "hello" 会输出 "hello world"。只是一种将变量注入字符串的简单方法。
    • 感谢大侠的解释,非常感谢您的详细解释!我会研究你的答案和其他人,因为我不熟悉这些!
    【解决方案7】:
    def cmp(item1, item2):
        if item2 == item1:
            return "{} is equal to {}".format(item2, item1)
        elif item2 >= item1:
            return "{} is greater than {}".format(item2, item1)
        elif item2 <= item1:
            return "{} is less than {}".format(item2, item1)
        else:
            return "Invalid item(s)."
    
    
    x = [1, 3, 2, 5, 7]
    
    for i in range(len(x)-1):
        print(cmp(x[i],x[i+1]))
    

    【讨论】:

      【解决方案8】:

      可以只使用for循环和三元运算符,如下所示;

      x = [1, 3, 2, 5, 7]
      for i in range(len(x)-1):
          comparison = "greater than" if x[i+1]>x[i] else ("equal to" if x[i+1]==x[i] else "less than")
          print("The value {0} is {1} {2}.".format(x[i+1],comparison,x[i]))
      

      【讨论】:

      • 感谢您的编辑,但与我的另一个编辑存在冲突。不过,通常最好对答案发表评论而不是直接编辑它(没有冒犯!)
      猜你喜欢
      • 1970-01-01
      • 2022-01-13
      • 1970-01-01
      • 2011-09-05
      • 2013-11-25
      • 2018-09-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多