社区所有版块导航
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
反馈   公告   社区推广  
产品
短视频  
印度
印度  
私信  •  关注

martineau

martineau 最近创建的主题
martineau 最近回复了

关于你的 编辑 如果使用元类,我建议使用 dict 而不是 set 对于 bucket

class MetaBucket(type):
    def __init__(cls, name, bases, dct):
        cls.bucket = {}

    def __getitem__(cls, id):
        return cls.bucket[id]

    def __setitem__(cls, id, name):
        cls.bucket[id] = name


class Bucket(metaclass=MetaBucket):
    def __init__(self, id, name):
        self.bucket[id] = name


b = Bucket("foo", "bar")
print(3, Bucket["foo"])  # -> 3 bar
print(4, Bucket["nonesuch"])  # -> KeyError: 'nonesuch'

以下内容对我很有用(尽管医生警告我不要从 stdout ).包装 斯特杜特 带着 io.TextIOWrapper() 支持字段数据中嵌入的换行符。

这样做可以使用发电机,其优点是 斯特杜特 一次读一行。

p2 = subprocess.Popen(["sort", "tabbed.csv"], stdout=subprocess.PIPE)
output = io.TextIOWrapper(p2.stdout, newline=os.linesep)
edits = csv.reader((line for line in output), delimiter="\t")
for row in edits:
    print(row)

输出:

['1', '2', '3', '4']
['5', '6', '7', '8']
['9', '10', '11', '12']
['a', 'b\r\nx', 'c', 'd']

这个 tabbed.csv 输入测试文件包含以下内容(其中 » 表示制表符和 ≡ 换行符):

1»2»3»4
9»10»11»12
a»"b≡x"»c»d
5»6»7»8
3 年前
回复了 martineau 创建的主题 » 在python中按列表存储项

你不断得到“无效”的原因是,你没有以一致的方式处理用户的输入 Sign_up() Sign_in() 功能。更新列表的一种方法 lists_module 是通过使用 atexit 模块注册脚本结束时将执行的函数。

import atexit
import lists_module


def Sign_in():
    email = input("Enter Your Email ").strip().capitalize()
    password = input("Enter your password ").strip().capitalize()

    if email in lists_module.emails and password in lists_module.passwords:
        print("success")
    else:
        print("invalid")

def Sign_up():
    first_name = input("Enter Your First Name ").strip().capitalize()
    last_name = input("Enter Your Last Name ").strip().capitalize()
    new_email = input("Enter Your Email ").strip().capitalize()
    new_password = input("Enetr New Password ").strip().capitalize()
    lists_module.Fname.append(first_name)
    lists_module.Lname.append(last_name)
    lists_module.emails.append(new_email)
    lists_module.passwords.append(new_password)

    print("Sign-In Page")
    Sign_in()

def update_lists_module():
    with open('lists_module.py', 'w') as outp:
        for name in dir(lists_module):
            if not name.startswith('_'):
                value = getattr(lists_module, name)
                outp.write(f'{name} = {value!r}\n')


atexit.register(update_lists_module)
Sign_up()

问题在于列表中的每一行都是从 readlines() 有一个尾随的新行,所以 if user_master == "test" 失败。最简单的修复方法是利用内置的 str,splitlines() 方法:

with open('infos.txt', 'r') as f:
    lines = f.read().splitlines()  # Create list of lines with newlines stripped.

user_master = lines[0]
print(user_master) # -> test

if user_master == "test":
    print("OK") # This now works.
3 年前
回复了 martineau 创建的主题 » 使用Python中的itertools将不同硬币命名的组合汇总为目标值

你可以用 list comprehension 为了掩盖事实,你真的 需要使用嵌套 for 循环以通用方式解决此问题(避免可能需要硬编码 很大 数量(非嵌套的):

from itertools import chain, combinations

ones = [1, 1, 1]   # 3 coins of value 1
twos = [2, 2]      # 2 coins of value 2
fives = [5, 5, 5]  # 3 coins of value 5
all_coins = ones + twos + fives
target = 10

combos = set()
for combo in chain.from_iterable(combinations(all_coins, length)
                                    for length in range(1, len(all_coins)+1)):
    if sum(combo) == target:
        combos.add(combo)

print(combos)

通过添加一个助手函数,可以以更可读的方式打印结果:

from itertools import groupby

denomination = {1: 'ones', 2: 'twos', 5: 'fives'}  # Names of values.

def ppcombo(combo):
    """ Pretty-print a combination of values. """
    groups, uniquekeys = [], []
    combo = sorted(combo)
    for key, group in groupby(combo):
        groups.append(list(group))
        uniquekeys.append(key)
    counts = {key: len(group) for key, group in zip(uniquekeys, groups)}
    print(' + '.join(f'{count}*{denomination[value]}' for value, count in counts.items()))

print('combos:', combos)
print()
for combo in combos:
    ppcombo(combo)

样本输出:

combos: {(1, 2, 2, 5), (5, 5), (1, 1, 1, 2, 5)}

1*ones + 2*twos + 1*fives
2*fives
3*ones + 1*twos + 1*fives
5 年前
回复了 martineau 创建的主题 » 如何根据python中的种子生成特定大小的密钥

这里有一个函数,可以用来将字节字符串中的值分成指定大小的元组。字节字符串首先作为整数列表输出,然后是与之对应的元组列表。请注意,在示例中,最后一个元组的最后两个值除以3后,是如何用零填充的,因为字节字符串长度(16)不是该值的倍数。在将其分成大小为4的元组时不会发生这种情况(因此没有附加填充值)。

还要注意 grouper() itertools documentation .

from itertools import zip_longest

def grouper(n, iterable, fillvalue=None):
    "s -> (s0, s1...sn-1), (sn, sn+1...s2n-1), (s2n, s2n+1...s3n-1), ..."
    return zip_longest(*[iter(iterable)]*n, fillvalue=fillvalue)

aes_key = b'\x80in\xbe\x06b\x8f\x8fZ}l-\xb4j\xb5\x1f'

ints = list(aes_key)
print(ints)

tuples = list(grouper(3, aes_key, fillvalue=0))
print(tuples)

tuples = list(grouper(4, aes_key, fillvalue=0))
print(tuples)

[128, 105, 110, 190, 6, 98, 143, 143, 90, 125, 108, 45, 180, 106, 181, 31]
[(128, 105, 110), (190, 6, 98), (143, 143, 90), (125, 108, 45), (180, 106, 181), (31, 0, 0)]
[(128, 105, 110, 190), (6, 98, 143, 143), (90, 125, 108, 45), (180, 106, 181, 31)]

由于您似乎想用这些数据制作一个图像,您可能仍然需要根据图像每行中像素的数量进一步格式化该数据。

可以将元组列表转换回如下所示的字节字符串:

# To convert a list of tuples back into a byte string.
from itertools import chain
print(bytes(chain.from_iterable(tuples)))

输出:

b'\x80in\xbe\x06b\x8f\x8fZ}l-\xb4j\xb5\x1f'

但是,如果没有添加填充值,这将只与原始字节字符串相同(与使用4元组的情况一样)。

5 年前
回复了 martineau 创建的主题 » Python:named tuple.\u source在Python 3.7中不工作

是的,如前所述 here ,属性 _source 已从中删除 namedtuples 在Python3.7中。

在版本3.7中更改: 移除 冗长的 参数和 _来源 属性。

5 年前
回复了 martineau 创建的主题 » 如何在python中跳过读取CSV文件的第一行?

您可以使用 csv 模块的 Sniffer 类来推断CSV文件的格式,并检测是否存在头行以及内置的 next() 函数仅在必要时跳过第一行:

import csv

with open('all16.csv', 'r', newline='') as file:
    has_header = csv.Sniffer().has_header(file.read(1024))
    file.seek(0)  # Rewind.
    reader = csv.reader(file)
    if has_header:
        next(reader)  # Skip header row.
    column = 1
    datatype = float
    data = (datatype(row[column]) for row in reader)
    least_value = min(data)

print(least_value)

自从 datatype column 在您的示例中是硬编码的,处理 row 这样地:

    data = (float(row[1]) for row in reader)

注: 上面的代码适用于Python3.x。对于Python2.x,请使用以下行打开文件,而不是显示:

with open('all16.csv', 'rb') as file:
5 年前
回复了 martineau 创建的主题 » Python Tkinter输出文本到文本小部件

这里有一些东西,使用多线程,似乎做你想要的。主程序分为处理QUI的部分和单独的 workerthread 管理ping的 subprocess ,从中收集结果并将其放入 Queue 其内容定期传输到GUI。

它使用 time.sleep() 因为它是在一个单独的线程中完成的 用tkinter就行了。

注意,您可能需要在GUI中添加一个垂直滚动条。

import subprocess
import queue
import threading
import time
import tkinter as tk


class GuiPart:
    def __init__(self, master, queue, end_command):
        self.queue = queue
        self.master = master
        self.textbox = tk.Text(root)
        self.textbox.pack()
        btn = tk.Button(master, text='Quit', command=end_command)
        btn.pack(expand=True)

    def process_incoming(self):
        """ Handle all messages currently in the queue. """
        while self.queue.qsize():
            try:
                info = self.queue.get_nowait()
                self.textbox.insert(tk.INSERT, info)
            except queue.Empty:  # Shouldn't happen.
                pass


class ThreadedClient:
    """ Launch the main part of the GUI and the worker thread.
        periodic_call() and end_application() could reside in the GUI part, but
        putting them here keeps all the thread controls in a single place.
    """
    def __init__(self, master):
        self.master = master
        self.queue = queue.Queue()

        # Set up the GUI part.
        self.gui = GuiPart(master, self.queue, self.end_application)

        # Set up the background processing thread.
        self.running = True
        self.thread = threading.Thread(target=self.workerthread)
        self.thread.start()

        # Start periodic checking of the queue.
        self.periodic_call(200)

    def periodic_call(self, delay):
        """ Every delay ms process everything new in the queue. """
        self.gui.process_incoming()
        if not self.running:
            sys.exit(1)
        self.master.after(delay, self.periodic_call, delay)

    # Runs in separate thread - NO tkinter calls allowed.
    def workerthread(self):
        while self.running:
            with open('servers.txt', 'r') as file:
                for ip in file:
                    rc = subprocess.Popen(["ping", "-c", "7", "-n", "-W", "2", ip]).wait()
                    if rc:
                        self.queue.put('ip address {} is inactive\n'.format(ip))
                    time.sleep(1)

    def end_application(self):
        self.running = False  # Stop queue checking.
        self.master.quit()


if __name__ == '__main__':
    root = tk.Tk()
    root.title('Pinger')
    client = ThreadedClient(root)
    root.mainloop()  # Display application window and start tkinter event loop.
6 年前
回复了 martineau 创建的主题 » 将python日历插入tkinter标签

问题之一是您没有调用 mainloop 因为你忽略了 () . 另一个是你没有给标签一个位置。

#! /usr/bin/env python
import calendar
import tkinter as tk
def CalScr():
    calendar2019 = calendar.calendar(2019) #creating calender variable
    root4 = tk.Tk()
    labelCalen= tk.Label(root4, text = calendar2019, font=("Courier New", 14))
    labelCalen.grid(column=0, row=0)
    root4.mainloop()
CalScr()

这也将字体设置为固定间距,否则日历将无法正确对齐。