小编bin*_*bjz的帖子

Python:如何在Class中动态分配函数名称

我有一个关于如何在Class中动态分配函数名称的问题.

例如:

If a class wants to be used for "for...in" loop, similar to a list
or a tuple, you must implement an __iter__ () method

python2.x will use __iter__() and next(),
python3.x need to use __iter__() and __next__()
Run Code Online (Sandbox Code Playgroud)

码:

样本的纤维蛋白数量在10以内

class Fib(object):
    def __init__(self):
        self.a, self.b = 0, 1

    def __iter__(self):
        return self

    if sys.version_info[0] == 2:
        iter_n = 'next'  #if python version is 2.x
    else:
        iter_n = '__next__'  #if python version is 3.x

    print('iter_n value is ', iter_n) …
Run Code Online (Sandbox Code Playgroud)

python

2
推荐指数
1
解决办法
156
查看次数

python3:在map中使用三元运算符,它将返回None

对于python 2.7.13

>>> lst_ = [1]
>>> map(lambda x, y: x + y if y else 1, lst_, lst_[1:])
[1]
Run Code Online (Sandbox Code Playgroud)

对于python 3.6.1

>>> lst_ = [1]
>>> list(map(lambda x, y: x + y if y else 1, lst_, lst_[1:]))
[]
Run Code Online (Sandbox Code Playgroud)

两个问题:

  • 我想知道为什么python2返回正确的结果,但python3返回None

  • 我应该如何使用python3修改代码以返回正确的结果

python functional-programming python-3.x

2
推荐指数
1
解决办法
283
查看次数

如何将字符串插入文件的倒数第二行

我有一个关于如何将字符串插入文件的倒数第二行的问题.

例如:

$ cat diff_a.txt
students
teacher
mike
john

$ cat diff_b.txt
python
bash shell
Java
Run Code Online (Sandbox Code Playgroud)

预期结果应为:

$ cat diff_b.txt
python
bash shell
mike
Java
Run Code Online (Sandbox Code Playgroud)

如果我使用以下命令,它会将字符串"mike"追加到diff_b.txt的最后一行

$ grep mike diff_a.txt >> diff_b.txt
$ cat diff_b.txt
python
bash shell
Java
mike
Run Code Online (Sandbox Code Playgroud)

题:

How should I put "mike" into second to last line of diff_b.txt ?
Run Code Online (Sandbox Code Playgroud)

bash awk sed

-1
推荐指数
1
解决办法
2438
查看次数

标签 统计

python ×2

awk ×1

bash ×1

functional-programming ×1

python-3.x ×1

sed ×1