小编wwi*_*wii的帖子

\ v与\ x0b或\ x0c的区别如何?

键入string.whitespace为您提供一个字符串,其中包含Python string模块定义的所有空白字符:

'\t\n\x0b\x0c\r '
Run Code Online (Sandbox Code Playgroud)

双方\x0b\x0c似乎给了一个垂直的标签.

>>> print 'first\x0bsecond'
first
     second
Run Code Online (Sandbox Code Playgroud)

\v给出了同样的效果.这三种有什么不同?为什么string模块使用\x0b\x0c更简单\v

python string whitespace escaping

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

Numpy:使用reshape或newaxis添加尺寸

任一ndarray.reshapenumpy.newaxis可用于一个新的维度添加到一个数组.他们似乎都创造了一个观点,使用一个而不是另一个是否有任何理由或优势?

>>> b
array([ 1.,  1.,  1.,  1.])
>>> c = b.reshape((1,4))
>>> c *= 2
>>> c
array([[ 2.,  2.,  2.,  2.]])
>>> c.shape
(1, 4)
>>> b
array([ 2.,  2.,  2.,  2.])
>>> d = b[np.newaxis,...]
>>> d
array([[ 2.,  2.,  2.,  2.]])
>>> d.shape
(1, 4)
>>> d *= 2
>>> b
array([ 4.,  4.,  4.,  4.])
>>> c
array([[ 4.,  4.,  4.,  4.]])
>>> d
array([[ 4.,  4.,  4.,  4.]])
>>> 
Run Code Online (Sandbox Code Playgroud)

`

python numpy

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

TypeError: An asyncio.Future, a coroutine or an awaitable is required

I'm trying to make an asynchronous web scraper using beautifulsoup and aiohttp.This is my initial code to start things.I'm getting a [TypeError: An asyncio.Future, a coroutine or an awaitable is required] and having a hard time figuring out what is wrong with my code.I am new to python and would appreciate any help regarding this.

import bs4
import asyncio
import aiohttp


async def parse(page):
    soup=bs4.BeautifulSoup(page,'html.parser')
    soup.prettify()
    print(soup.title)



async def request():
    async with aiohttp.ClientSession() as session:
        async with session.get("https://google.com") as resp: …
Run Code Online (Sandbox Code Playgroud)

python asynchronous python-3.x python-asyncio aiohttp

9
推荐指数
1
解决办法
1万
查看次数

模拟side_effect迭代器可以在耗尽后重置吗?

mock.reset_mock()不会重置副作用迭代器.有没有办法在不再创建模拟的情况下执行此操作?

>>> from mock import MagicMock
>>> mock = MagicMock(side_effect = [1,2])
>>> mock(), mock()
(1, 2)
>>> mock()

Traceback (most recent call last):
  File "<pyshell#114>", line 1, in <module>
    mock()
  File "C:\Python27\Lib\site-packages\mock.py", line 955, in __call__
    return _mock_self._mock_call(*args, **kwargs)
  File "C:\Python27\Lib\site-packages\mock.py", line 1013, in _mock_call
    result = next(effect)
StopIteration
>>> mock.reset_mock()
>>> mock()

Traceback (most recent call last):
  ...
StopIteration
>>> mock = MagicMock(side_effect = [1,2])
>>> mock(), mock()
(1, 2)
>>> 
Run Code Online (Sandbox Code Playgroud)

目的是在后续测试中重用模拟,但我怀疑,像生成器一样,它无法重新启动.

在指向正确的方向后,我看到(mock.py并且从不迟到),发现它 …

python unit-testing mocking python-2.7

8
推荐指数
1
解决办法
5676
查看次数

计算Python中的直方图峰

在Python中,如何计算直方图的峰值?

我尝试了这个:

import numpy as np
from scipy.signal import argrelextrema

data = [0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 1, 2, 3, 4,

        5, 6, 7, 8, 9, 5, 6, 7, 8, 9, 5, 6, 7, 8, 9,

        12,

        15, 16, 17, 18, 19, 15, 16, 17, 18, 

        19, 20, 21, 22, 23, 24,]

h = np.histogram(data, bins=[0, 5, 10, 15, 20, 25])
hData = h[0]
peaks = argrelextrema(hData, np.greater)
Run Code Online (Sandbox Code Playgroud)

但是结果是:

(array([3]),) …
Run Code Online (Sandbox Code Playgroud)

python

6
推荐指数
3
解决办法
8115
查看次数

过滤嵌套列表

我想用另一个可变长度的列表过滤嵌套列表.如果子列表中的任何项与筛选器列表的任何元素匹配,则应排除子列表.以下代码对我有用,但是这个任务有一个"更清洁"的解决方案吗?

the_list = [['blue'], ['blue', 'red', 'black'], ['green', 'yellow'], ['yellow', 'green'], ['orange'], ['white', 'gray']]
filters = ['blue', 'white']

filtered_list = []
for sublist in the_list:
    for item in sublist:
        if item in filters:
            break
        filtered_list.append(sublist)
        break
Run Code Online (Sandbox Code Playgroud)

预期产量:

filtered_list = [['green', 'yellow'], ['yellow', 'green'], ['orange']]
Run Code Online (Sandbox Code Playgroud)

python filter nested-lists

6
推荐指数
1
解决办法
1718
查看次数

如何在python中找到拐点?

我有一个 RGB 图像的直方图,它表示三个分量 R、G 和 B 的三个曲线。我想找到每条曲线的拐点。我使用二阶导数来找到它们,但我不能,二阶导数不会取消其返回空值。那么如何找到拐点呢?有没有其他方法可以找到它们?

在此处输入图片说明

import os, cv2, random
import numpy as np
import matplotlib.pyplot as plt
import math
from sympy import *

image = cv2.imread('C:/Users/Xers/Desktop/img.jpg')

CHANNELS = ['r', 'g', 'b']

for i, channel in enumerate( CHANNELS ):
    

  histogram = cv2.calcHist([image], [i], None, [256], [0,256])

  histogram = cv2.GaussianBlur( histogram, (5,5), 0)

  plt.plot(histogram, color = channel)

     
  x= plt.xlim([0,256])
  y = plt.ylim([0, 24000])


  derivative1= np.diff(histogram, axis=0)
  derivative2= np.diff(derivative1, axis=0)

  inf_point = np.where ( derivative2 == 0)[0]
  print(inf_point)
plt.show()
Run Code Online (Sandbox Code Playgroud)

python arrays opencv

6
推荐指数
1
解决办法
4787
查看次数

numpy数组乘法与任意维度的数组

我有一个numpy数组A,它有形状(10,).

我也有,作为此时的,具有形状(10,3,5)一个numpy的数组B中.我想在这两者之间进行乘法以得到C,使得C [0,:,] = A [0]*B [0,:,],C [1] = A [1]*B [1 ,:,]]等

我不想用循环来解决这个问题,其中一个原因是事物的美学,另一个原因是这个代码需要非常通用.我希望用户能够输入几乎任何形状的任何B,只要前导尺寸为10.例如,我希望用户能够放入形状B(10,4).

那么:如何使用numpy实现这种乘法?谢谢.

ADDENDUM:有人问过例子.会变小.假设A是numpy数组[1,2,3],B是numpy数组[[1,2],[4,5],[7,8]].我希望两者的乘法得到[[1,2],[8,10],[21,24]]....

>>> a
array([1, 2, 3])
>>> b
array([[1, 2],
       [4, 5],
       [7, 8]])
>>> #result
>>> c
array([[ 1,  2],
       [ 8, 10],
       [21, 24]])
>>>
Run Code Online (Sandbox Code Playgroud)

python arrays numpy multiplication

5
推荐指数
1
解决办法
853
查看次数

python - 用两个不同列表中的值替换列表的布尔值

我有一个布尔值的列表,如

lyst = [True,True,False,True,False]
Run Code Online (Sandbox Code Playgroud)

和两个不同的列表,例如:

car = ['BMW','VW','Volvo']
a = ['b','c']
Run Code Online (Sandbox Code Playgroud)

我只想将值替换为True,将carFalse替换为值a.或使从序列的新列表lyst和值从cara.结果应该是

[BMW,VW,b,Volvo,c].
Run Code Online (Sandbox Code Playgroud)

我的代码到目前为止:

for elem1,elem2,elem3 in zip(lyst,car,a):
    subelem2=elem2
    subelem3=elem3
    if elem1 != True:
        result_list.append(subelem2)
    else: 
        result_list.append(subelem3)
Run Code Online (Sandbox Code Playgroud)

但这会创建一个长于5的列表匹配.

我怎样才能做到这一点?

python replace boolean list

5
推荐指数
2
解决办法
1915
查看次数

python:如果列表中的值共享第一个单词,则对它们求和

我有一个清单如下,

flat_list = ['hello,5', 'mellow,4', 'mellow,2', 'yellow,2', 'yellow,7', 'hello,7', 'mellow,7', 'hello,7']
Run Code Online (Sandbox Code Playgroud)

如果它们共享相同的单词,我想获得值的总和,所以输出应该是,

期望的输出:

l = [('hello',19), ('yellow', 9), ('mellow',13)]
Run Code Online (Sandbox Code Playgroud)

到目前为止,我已经尝试过以下操作,

new_list = [v.split(',') for v in flat_list]

d = {}
for key, value in new_list:
   if key not in d.keys():
      d[key] = [key]
   d[key].append(value)

# getting rid of the first key in value lists
val = [val.pop(0) for k,val in d.items()]
# summing up the values
va = [sum([int(x) for x in va]) for ka,va in d.items()]
Run Code Online (Sandbox Code Playgroud)

但是由于某种原因,最后的总结不起作用,我没有得到我想要的输出

python dictionary sum list

5
推荐指数
1
解决办法
299
查看次数