社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Mark Tolonen  »  全部回复
回复总数  11
3 年前
回复了 Mark Tolonen 创建的主题 » 如何在python中将一串键值转换为正确的dict?

另一种方法是 re.split .在单词上拆分,后跟冒号,并可选地用空格包围,捕获单词:

>>> s = 'address: C/O John Smith @ Building X, S/W city: new york state: new york    population:        500000'
>>> re.split('\s*(\w+):\s*',s)
['', 'address', 'C/O John Smith @ Building X, S/W', 'city', 'new york', 'state', 'new york', 'population', '500000']

开头会有一个空字符串, zip 向上交替设置键和值,并转换为 dict :

>>> x=re.split('\s*(\w+):\s*',s)
>>> dict(zip(x[1::2],x[2::2]))
{'address': 'C/O John Smith @ Building X, S/W', 'city': 'new york', 'state': 'new york', 'population': '500000'}

你必须完全匹配论点。设定 .argtypes .restype 你使用的每一个函数 ctypes 可以正确地将参数封送到C并再次封送回来。如果你不设定 .重新键入 ctypes 假设返回值为 c_int (通常是有符号的32位整数)而不是(可能是64位)指针。

下面是一个有效的例子。我并没有充实每个函数,因为一个函数应该足够了。在32位和64位Python上进行了测试。

测验cpp(使用MS编译器cl/LD/EHsc/W4 test.cpp构建):

#include <stdio.h>

// Needed to export functions on Windows
#ifdef _WIN32
#   define API __declspec(dllexport)
#else
#   define API
#endif

class CMatrix
{
public:
    CMatrix(int d1) : s1(d1) { m = new float[d1]; }
    ~CMatrix() { delete [] m; }
    const float* Get(int& s) { s = s1; return m; }
    void Set(int x, float f) { m[x] = f; }
    int s1;
    float *m;
};

extern "C" {
    API CMatrix* CMatrix_new(int i) {return new CMatrix(i); }
    API const float* CMatrix_Get(CMatrix* cm, int& x) { return cm->Get(x); }
    API void CMatrix_Set(CMatrix* cm, int x, float f) { cm->Set(x, f); }
    API void CMatrix_delete(CMatrix* cm) { delete cm; }
}

测验py

import ctypes as ct

# For type checking the returned pointer.
class _CMatrix(ct.c_void_p) : pass
PCMatrix = ct.POINTER(_CMatrix)

class CMatrix:

    _dll = ct.CDLL('./test')
    _dll.CMatrix_new.argtypes = ct.c_int, 
    _dll.CMatrix_new.restype = PCMatrix
    _dll.CMatrix_Get.argtypes = PCMatrix, ct.POINTER(ct.c_int)
    _dll.CMatrix_Get.restype = ct.POINTER(ct.c_float)
    _dll.CMatrix_Set.argtypes = PCMatrix, ct.c_int, ct.c_float
    _dll.CMatrix_Set.restype = None
    _dll.CMatrix_delete.argtypes = PCMatrix, 
    _dll.CMatrix_delete.restype = None

    def __init__(self, i):
        self.obj = self._dll.CMatrix_new(i)

    def Set(self, x, f):
        self._dll.CMatrix_Set(self.obj, x, f)

    def Get(self):
        size = ct.c_int()
        m = self._dll.CMatrix_Get(self.obj, ct.byref(size))
        return m[:size.value]

    def __del__(self):
        self._dll.CMatrix_delete(self.obj)

cm = CMatrix(2)
cm.Set(0, 1.5)
cm.Set(1, 2.5)
print(cm.Get())

输出:

[1.5, 2.5]

看到了吗 bytes.hex() :

>>> import struct
>>> struct.pack('2I',12,30).hex()   # available since Python 3.5
'0c0000001e000000'
>>> struct.pack('2I',12,30).hex(' ')  # separator available since Python 3.8
'0c 00 00 00 1e 00 00 00'
>>> struct.pack('2I',12,30).hex(' ',4) # bytes_per_sep also since Python 3.8
'0c000000 1e000000'

较老的Python使用 binascii.hexlify :

>>> import binascii
>>> import struct
>>> binascii.hexlify(struct.pack('2I',12,30))
b'0c0000001e000000'

或者,如果希望使用空格使其更具可读性:

>>> ' '.join(format(n,'02X') for n in struct.pack('2I',12,33))
'0C 00 00 00 21 00 00 00'

Python 3.6+,使用f字符串(但是 .hex() 是可用且更容易的)。

>>> ' '.join(f'{n:02X}' for n in struct.pack('2I',12,33))
'0C 00 00 00 21 00 00 00'
5 年前
回复了 Mark Tolonen 创建的主题 » Python遍历布尔变量的所有可能组合

itertools.product 可以生成所有组合:

import itertools

names = 'is_A is_B is_C is_D is_E is_F'.split()

def my_func(params):
    print(params)

for p in itertools.product([True,False],repeat=6):
    params = dict(zip(names,p))
    my_func(params)

输出:

{'is_A': True, 'is_B': True, 'is_C': True, 'is_D': True, 'is_E': True, 'is_F': True}
{'is_A': True, 'is_B': True, 'is_C': True, 'is_D': True, 'is_E': True, 'is_F': False}
...
{'is_A': False, 'is_B': False, 'is_C': False, 'is_D': False, 'is_E': False, 'is_F': True}
{'is_A': False, 'is_B': False, 'is_C': False, 'is_D': False, 'is_E': False, 'is_F': False}
6 年前
回复了 Mark Tolonen 创建的主题 » SWIG错误编码的字符串导致Python崩溃

无法复制。编辑问题并添加 Minimal, Complete, Verifable Example 如果此示例无法解决您的问题并需要进一步帮助:

%module test

%include <std_string.i>

%inline %{
#include <string>

std::string func(std::string s)
{
    return '[' + s + ']';
}
%}

演示:

Python 3.3.5 (v3.3.5:62cf4e77f785, Mar  9 2014, 10:35:05) [MSC v.1600 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import test
>>> test.func('ábc')
'[ábc]'
5 年前
回复了 Mark Tolonen 创建的主题 » 方法返回None,即使在python 3中value不是None[duplicate]

递归有它的用途,但使用它重新开始不是其中之一。光着身子也不好。

如果需要循环,请使用循环。

如果需要捕获异常,请捕获 预期 例外。这样,如果发生意外异常,您就可以看到并处理该bug。

例子:

class Game:
    def set_val(self):
        while True:
            p1=input("Enter player 1 name:")
            if p1: break
        while True:
            p2=input("Enter player 2 name:")
            if p2: break

        # Loop until good input
        # int() will throw ValueError if input is not convertible to int.
        while True:
            try:
                goal=int(input("Enter a number to set goal:"))
                break # break from the loop if no exception
            except ValueError:
                print("Please give proper input")

        return p1,p2,goal

G=Game()

p1,p2,goal=G.set_val()
print(p1,p2,goal)
6 年前
回复了 Mark Tolonen 创建的主题 » 使用utf-8字符串写入文件时出现python编解码器错误

要明确。您已使用默认编码打开进行写入。不管是什么,它都不支持所有的unicode代码点。用utf-8编码打开文件,其中 支持所有Unicode代码点:

import io
with io.open('out3.txt','w',encoding='utf8') as outFile:
6 年前
回复了 Mark Tolonen 创建的主题 » 带python的udp套接字

如果您是udp侦听器,则 bind 插座的端口。如果您是发件人,则不需要绑定端口:

回音服务器

from socket import *

s = socket(type=SOCK_DGRAM)
s.bind(('localhost',5000))

while True:
    data,addr = s.recvfrom(1024)
    print(data,addr)
    s.sendto(data,addr)

客户机

from socket import *

s = socket(type=SOCK_DGRAM)
s.sendto(b'hello',('localhost',5000))
data,addr = s.recvfrom(1024)
print(data,addr)

启动服务器,然后运行客户端。

客户端输出:

C:\>client.py
b'hello' ('127.0.0.1', 5000)

C:\>client.py
b'hello' ('127.0.0.1', 5000)

服务器输出:

C:\>server.py
b'hello' ('127.0.0.1', 50391)
b'hello' ('127.0.0.1', 50392)
6 年前
回复了 Mark Tolonen 创建的主题 » 元组由由SWIG生成的Python包装器返回为C++向量。

如果你使用 std_vector.i ,您将得到由 STD-向量 . 如果你不喜欢,你就得自己写排版图。

下面是一个类型映射,用于覆盖默认行为(无错误检查)并返回列表而不是元组:

%typemap(out) std::vector<int> (PyObject* obj) %{
    obj = PyList_New($1.size());
    for(auto i = 0; i < $1.size(); ++i)
        PyList_SET_ITEM(obj, i, PyLong_FromLong($1[i]));
    $result = SWIG_Python_AppendOutput($result, obj);
%}

当然你也可以 v = list(get_sweep_points()) 现在是一个列表:^)

6 年前
回复了 Mark Tolonen 创建的主题 » 当将Python元组传递到C++类型的C++函数时,分割错误11

定义 .argtypes .restype 为了你的职责。默认类型为 c_int (32位)并且您可能正在使用指针为64位的操作系统,截断 A* 返回值。

core_lib.create_A.argtypes = None
core_lib.create_A.restype = c_void_p
core_lib.set_size.argtypes = [c_void_p,POINTER(c_int)]
core_lib.set_size.restype = None

c_void_p 对于不透明指针就足够了。通过声明指向类的指针,并将大小指针声明为包含两个int的数组,可以获得更好的类型检查:

class A(Structure):
    pass

core_lib.create_A.argtypes = None
core_lib.create_A.restype = POINTER(A)
core_lib.set_size.argtypes = POINTER(A),POINTER(c_int * 2)
core_lib.set_size.restype = None

如果你有选择,我建议你定义 set_size 作为 void set_size(A* a, int x, int y) 所以你可以打电话给 a.set_size(3,3) 直接而不是创建 (c_int * 2)(3,3) 通过。

6 年前
回复了 Mark Tolonen 创建的主题 » 如何在python中获得utf-16(十进制)?

在Python2“窄”构建中,它非常简单:

>>> emoticon = u'\U0001f498'
>>> map(ord,emoticon)
[55357, 56472]

这在Python2(窄和宽版本)和Python3中都适用:

from __future__ import print_function
import struct

emoticon = u'\U0001f498'
print(struct.unpack('<2H',emoticon.encode('utf-16le')))

输出:

(55357, 56472)

这是一个更通用的解决方案,可以为任意长度的字符串打印utf-16代码点:

from __future__ import print_function,division
import struct

def utf16words(s):
    encoded = s.encode('utf-16le')
    num_words = len(encoded) // 2
    return struct.unpack('<{}H'.format(num_words),encoded)

emoticon = u'ABC\U0001f498'
print(utf16words(emoticon))

输出:

(65, 66, 67, 55357, 56472)