小编Sha*_*ger的帖子

Python3 utf-8 解码问题

以下代码在我的 Windows 机器上使用 Python3 运行良好,并打印字符“é”:

data = b"\xc3\xa9"

print(data.decode('utf-8'))
Run Code Online (Sandbox Code Playgroud)

但是,在基于 Ubuntu 的 docker 容器上运行相同的结果:

UnicodeEncodeError: 'ascii' codec can't encode character '\xe9' in position 0: ordinal not in range(128)
Run Code Online (Sandbox Code Playgroud)

是否需要安装任何东西才能启用 utf-8 解码?

python linux windows utf-8 python-3.x

4
推荐指数
1
解决办法
5691
查看次数

我们如何验证python 3.7中编写的代码在pycharm中的python 3.6中是否可以正常工作?

我在pycharm中的python 3.7解释器中编写了代码,但我不知道如何验证它是否可以被3.6x解释?

python pycharm python-3.x

4
推荐指数
1
解决办法
72
查看次数

在python 3.6与旧版本中的字典顺序

我有这些代码,我需要按照这个确切的顺序打印出来(访客团队,访客评分,主页团队,家庭评级,预期获胜者,保证金)tabulate.

final_dict = {'Visitor Team': visitor_team, 'Visitor Rating': visitor_rating, 'Home Team': home_team,
              'Home Rating': home_rating, 'Expected Winner': expected_winner, 'Margin': expected_winner_diff}

print(tabulate(final_dict, headers="keys", floatfmt=".2f", tablefmt="fancy_grid"))
Run Code Online (Sandbox Code Playgroud)

我一直在学习和使用Python 3.6,而且我不知道,3.6中的dicts现在已经订购了,所以这实际上按照我的意图打印出来.这只是愚蠢的运气我想Python 3.6给了我我所需要的!

但我去另一台计算机上安装Python 3.5,这不会像我想的那样打印出来.我一直在阅读有关订单,但我不确定如何使用它.我是否需要首先将final_dict声明为空,然后迭代到我需要的关键顺序?

python dictionary python-3.x python-3.5 python-3.6

3
推荐指数
1
解决办法
555
查看次数

什么时候Python导入?

如果我import在一个if/else块中嵌套了语句,我是否会提高效率?我知道有些语言会对代码import和语法问题进行"一次通过" .我只是不确定Python是如何深入研究的.

我的假设

由于Python是通过import在else块中嵌套语句来解释而不是编译的,因此在到达该行之前不会导入这些库,因此除非另有需要,否则将节省系统资源.

脚本

我编写了一个脚本,这个脚本将被更多的计算机文化使用,而那些则更少.我的部门非常熟悉从命令行运行带有参数的脚本,所以我已经设置它来获取它需要的参数,如果它没有找到它期望的参数,它将启动带有标题,按钮的GUI,和更详细的说明.但是,这意味着我正在导入仅在未提供参数的情况下使用的库.

附加信息

  • GUI是非常非常基本的(六个文本字段和可能更少的按钮)所以我不关心只是创建和生成一个自定义GUI类,其中将导入必要的库.如果这变得更复杂,我将来会考虑它,甚至推动改变为web界面.
  • 我的脚本完全按照我的预期运行.问题只是资源消耗.

python python-import python-3.x

3
推荐指数
1
解决办法
74
查看次数

字典在迭代过程中更改了大小-代码在Py2中有效,而在Py3中无效

我有以下示例代码:

k_list = ['test', 'test1', 'test3']

def test(*args, **kwargs):
    for k, value in kwargs.items():
        if k in k_list:
            print("Popping k = ", k)
            kwargs.pop(k, None)
    print("Remaining KWARGS:", kwargs.items())

test(test='test', test1='test1', test2='test2', test3='test3')
Run Code Online (Sandbox Code Playgroud)

在Python 2.7.13中,这完全可以打印出我所期望的内容,并且仍然在kwargs

('Popping k = ', 'test')
('Popping k = ', 'test1')
('Popping k = ', 'test3')
('Remaining KWARGS:', [('test2', 'test2')])
Run Code Online (Sandbox Code Playgroud)

但是,在Python 3.6.1中,此操作失败:

Popping k =  test
Traceback (most recent call last):
  File "test1.py", line 11, in <module>
    test(test='test', test1='test1', test2='test2', test3='test3')
  File "test1.py", line 5, …
Run Code Online (Sandbox Code Playgroud)

python dictionary python-2.7 python-3.x

3
推荐指数
2
解决办法
3218
查看次数

为什么使用 __slots__ 时默认删除 __weakref__ ?

我认为主要目的__slots__是通过允许显式指定属性来节省内存使用量,而不是允许__dict__在实例上动态分配属性。所以我以某种方式理解为什么__dict__在使用时默认删除__slots__。但为什么它同时__weakref__默认删除呢?

参考: https: //docs.python.org/3/reference/datamodel.html#slots

python weak-references slots

3
推荐指数
1
解决办法
194
查看次数

list.count() 与 Counter() 性能

在尝试查找字符串中一堆字符的频率时,为什么对 4 个不同的字符运行 string.count(character) 4 次会比使用 collections.Counter(string) 产生更快的执行时间(使用 time.time()) )?

背景:给定由字符串表示的一系列动作。有效移动为 R(右)、L(左)、U(上)和 D(下)。如果移动顺序带我回到原点,则返回 True。否则,返回 false。


# approach - 1 : iterate 4 times (3.9*10^-6 seconds)
def foo1(moves):
    return moves.count('U') == moves.count('D') and moves.count('L') == moves.count('R')

# approach - 2 iterate once (3.9*10^-5 seconds)
def foo2(moves): 
    from collections import Counter
    d = Counter(moves)
    return d['R'] == d['L'] and d['U'] == d['D']

import time
start = time.time()
moves = "LDRRLRUULRLRLRLRLRLRLRLRLRLRL"
foo1(moves)
# foo2(moves)
end = time.time()
print("--- %s seconds ---" % (end …
Run Code Online (Sandbox Code Playgroud)

counter performancecounter count performance-testing python-3.x

3
推荐指数
1
解决办法
3397
查看次数

是否可以保证这将是一个生成器?

def city_generator():
    print("city gen called")
    return 1  # <--- over simplified to drive the point of the question
    yield "amsterdam"
    yield "los angeles"

>>> citygenobj = city_generator()
>>> print(citygenobj)
<generator object city_generator at 0x02CE73B0>
>>> next(citygenobj)
city gen called
Traceback (most recent call last):
  File "<pyshell#137>", line 1, in <module>
    next(citygenobj)
StopIteration: 1
Run Code Online (Sandbox Code Playgroud)

问题:此函数是否充当生成器是否取决于python实现?还是python语言规范保证如果您有一条yield语句,则无论生成器是否yield可达,它都是生成器?

python yield generator python-3.x

3
推荐指数
1
解决办法
41
查看次数

如何将0/1转换为有效签名?

看下面的函数,其中a是一个无符号字节0-255,b是一个浮点数:

def convert(a, b):
    if a & 0x80:
        return -b
    return b
Run Code Online (Sandbox Code Playgroud)

它否定b了的第一位a,但没有设置时什么也不做。可能会认为这不是很酷,因为条件语句破坏了CPU中的分支预测。因此,人们将尝试将其转换为一种计算。

但是我只找到了这种解决方案,看起来效率不高:

def convert(a, b):
    return (-1)**(a & 0x80) * b
Run Code Online (Sandbox Code Playgroud)

哪一个更有效?编译器会简化第二个吗?有没有更好的办法?

python optimization python-3.x

3
推荐指数
1
解决办法
65
查看次数

有什么方法可以让函数返回执行策略吗?

我最近一直在从事一个项目,遇到一个问题,我不想在小向量上使用std::execution::par,因为这会产生开销。

理论上来说,这可以通过返回std::execution::parstd::execution::seq的函数来解决,具体取决于向量的总大小乘以每个元素的大小,并将其与固定值进行比较。但问题是它们的类型不同,这意味着它们无法退回。我们也可以只返回一个布尔值是否值得并行,但这会导致讨厌的分支,我不希望这样。我只是想知道是否有一种方法可以巧妙地解决这个问题

c++ parallel-processing std c++17 c++20

3
推荐指数
1
解决办法
124
查看次数