python - 将奇数放在列表的连续元素中 : Python 3. 2

标签 python list function numbers

我正在学习 Python 入门类(class)。我正在参加期末练习,但我不知道该如何应对一道题。它问:

完成以下方法,将字符串 s 中找到的奇数放入列表 x 的连续元素中。

def assign(s):
    length = _____
    x = _____*[0]
    index = 0
    for j in range(_____):
        digit = int(s[j])  #convert to int digit
        if _____: #test for odd number
            x[_____] = digit
            __________
    print("The odd numbers are")
    for j in range(index):
        print(x[j])

我不知道这是否是它的措辞方式,但我不知道如何着手回答这个问题。我最好的猜测是:

def assign(s):
    length = len(s)
    x = length*[0]
    index = 0
    for j in range(s):
        digit = int(s[j])  #convert to int digit
        if _____: #test for odd number
            x[_____] = digit
            __________
    print("The odd numbers are")
    for j in range(index):
        print(x[j])

我不知道如何继续,或者我什至不知道是否正确开始。我不能改变任何已经存在的东西,我只能填补空白,而且他们都必须填写。有人知道如何做到这一点吗?

最佳答案

解决方法如下:

def assign(s):
    length = len(s)
    x = length*[0]
    index = 0
    for j in range(length):
        digit = int(s[j])  #convert to int digit
        if digit % 2: #test for odd number
            x[index] = digit
            index += 1

    print("The odd numbers are")
    for j in range(index):
        print(x[j])

你的开头是对的。一个关键点是变量 index 指向应该添加到列表 x 的下一个奇数。


但是请注意,提供给您的模板很糟糕:它完全违背了 Python 的精神。看起来像 C 代码被强加到 Python 中;这不是好的做法,因为 Python 提供了比 C 更强大的数据结构。这里是Pythonic 版本:

def assign(input_string):
    odd_digits = []
    for char in input_string:
        digit = int(char)  # Convert to integer
        if digit % 2:  # If the digit is odd
            odd_digits.append(digit)
    print("The odd digits are", *odd_digits, sep='\n')  # or: ("The odd digits are", odd_digits)

主要区别在于您拥有更少的变量:代码更易读,阅读代码时需要记住的变量更少。消失的变量本质上是索引:通常不需要它们(索引在 C 中很重要,因为 C 是“接近金属”的:它接近于需要索引的机器语言)。因此,不再需要跟踪输入字符串的 length

你也有更少的麻烦:在原始版本中,列表 x 包含许多基本上无用的 0(较慢的代码,也更难理解) .本质上,Python 列表 x 被迫像一个 C 数组:字符串调用列表中的奇数位数可变(变量大小),不适用于数组(固定大小)。

此外,代码更短这一事实使得阅读和编写起来更快!


正如 Jon 所建议的,更加 Pythonic 的版本在于使用列表理解:

def assign(input_string):
    odd_digits = [char for char in input_string if int(char) % 2]  # or: if char in '13579'
    print("The odd digits are", *odd_digits, sep='\n')  # or: ("The odd digits are", odd_digits)

这是一个很好的例子,说明为什么 Python 代码的编写和读取速度比 C 代码快得多。

关于python - 将奇数放在列表的连续元素中 : Python 3. 2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13907696/

相关文章:

python - 代码在pycharm中运行良好,但转换为exe时却不行

用于聚合 PyQt 信号的 Python 装饰器

c++ - 如何编写接受 std::vector 或 std::list 的函数?

function - 如何正确调用Powershell函数?

Python验证url转到页面

python - python中numpy.fft包的 "GPU version"是什么?

python - 这怎么是一个非序列?

list - 用于 Web 的长检查列表 ui 模式

php - 在 PHP 中使用基本函数

javascript - "string.match()"不是函数?