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

Patrick Artner

Patrick Artner 最近创建的主题
Patrick Artner 最近回复了
2 年前
回复了 Patrick Artner 创建的主题 » Python中特定年份的时差

你可以通过 .days 关于时间差:

import datetime

current_year = datetime.date.today().year
start_of_curr = datetime.date(current_year,1,1)
end_of_curr = datetime.date(current_year,12,31)

data = [(datetime.date(2021,1,1), datetime.date(2022,3,1),  12), 
        (datetime.date(2021,1,1), datetime.date(2021,6,1),  5)]

for runtime_start, runtime_end, months in data:

    # limit the used start/end dates
    frm = start_of_curr  if runtime_start < start_of_curr else runtime_start
    to = runtime_end if runtime_end <= end_of_curr else end_of_curr

    print(int(round((to-frm).days / ((end_of_curr-start_of_curr).days/12),0)), 
        "vs expected: ", months)

输出:

12 vs expected:  12
5 vs expected:  5
2 年前
回复了 Patrick Artner 创建的主题 » 在Python中,并非所有副本都会从文本文件中删除

第一行可能包含 'hello\n' -最后一行只包含 'hello' -它们不一样。

使用

line_seen = set()

with  open('a.txt', 'r') as f, open('out.txt', 'w') as w:

    for i in f:
        i = i.strip()            # remove the \n from line
        if i not in line_seen:
            w.write(i + "\n")
            line_seen.add(i)
2 年前
回复了 Patrick Artner 创建的主题 » Python将排序列表转换为字典,Google Colab和Pycharm中的差异

字典是一个继承的无序数据结构-周期。

python(*)中的词典是按插入排序的——放入其中的第一项也是第一个打印的项。

(*)Python3.7及以上版本的保留-3.7以下的dict可以随机排序,或者(实现细节)也可以插入排序。

How do I detect the Python version at runtime?

如果您使用的是python的早期版本>=3.1您可以使用 collections.ordereddict

4 年前
回复了 Patrick Artner 创建的主题 » 使用键参数对python中的列表排序

我的评论的完整例子

list.sort(reverse=True, key = lambda x: (x.rank, x.distance)) 应该有效-如果连续的x.rank相等,它将按距离升序排序-问题是:距离到什么…你不能做点之间的相对距离-更像是每个点到f.e.中心的总距离(0,0)[即一个预先计算的距离…]

class p:
    def __init__(self, r, d):
        self.rank = r
        self.distance = d
    def __str__(self):
        return f'{self.rank}|{self.distance}'
    def __repr__(self):
        return str(self)

ranks = [1,2,3]
distances = [10,30,10]

data = [p(r,d) for r in ranks for d in distances]

print(data)

# sort by max rank, min distance
data.sort(key=lambda x:(-x.rank, x.distance))

print(data)

输出:

# created data
[1|10, 1|30, 1|10, 2|10, 2|30, 2|10, 3|10, 3|30, 3|10]

# sorted by max rank, min distance
[3|10, 3|10, 3|30, 2|10, 2|10, 2|30, 1|10, 1|10, 1|30]
5 年前
回复了 Patrick Artner 创建的主题 » python列表的dict到dict列表的dict

覆盖数据-需要添加到其中:

for entry in data:
     name = entry.pop('name')
     n_dict[name] = entry  # this overwrites the value of name all the time

修复:

n_dict = {}
for entry in data:
     name = entry.pop('name')
     n_dict.setdefault(name,[])
     n_dict[name].append(entry)

(或使用 defaultdict from collections )比使用 dict.setdefault(...) -但对于你的数据样本,两者都应该有效。


输出:

{'test15': [{'loss': 3.9064058800099866, 'val_accuracy': 0.1878172606229782,
             'epoch': 0, 'val_loss': 3.8064255714416495, 
             'accuracy': 0.056027164736506485}, 
            {'loss': 3.7856348285448367, 'val_accuracy': 0.1878172606229782,
             'epoch': 1, 'val_loss': 3.5590925216674805, 
             'accuracy': 0.16129032566713356}], 
 'test14': [{'loss': 3.908684137519228, 'val_accuracy': 0.1878172606229782, 
             'epoch': 0, 'val_loss': 3.8432216644287114, 
             'accuracy': 0.04584040881114014}, 
            {'loss': 3.8308442072066873, 'val_accuracy': 0.1878172606229782, 
             'epoch': 1, 'val_loss': 3.4720854759216313, 
             'accuracy': 0.1612903245539738}]}
5 年前
回复了 Patrick Artner 创建的主题 » python中的简单monte carlo模拟

你可能不是 印刷 不管函数返回什么-这就是为什么它什么都不显示。

使用 print(roll()) 而不是 roll() 打印得到的结果。

循环太多,解决方案占用的内存空间太大。

考虑一下运气不好,必须掷1.000.000.000.000次才能得到前6个-你将在列表中保存1.000.000.000个其他数字。那是很多记忆。


你可以用 set 要记住看到的数字和一个计数器来计算查找所有数据所需的时间:

def roll(sides=6, n=1000):
    """Tests 'n' times to roll all numbers from 1 to 'sides' randomly.
    Returns average tries needed to see all numbers over 'n' tries."""
    trials = []   # collects all sinly tried counters

    for _ in range(n):
        seen = set()   # empty, will only ever store 6 elements at most
        tried = 0      # how long did it take to find all 6?
        while len(seen) < sides:  # use sides here as well
            seen.add(random.randint(1,sides))
            tried += 1
        trials.append(tried)

    return sum(trials)/n


print(roll())  

输出(4次启动):

14.878

14.694

14.732

14.516
5 年前
回复了 Patrick Artner 创建的主题 » 在python中计算列表中介于一个范围之间的浮动数

你可以使用一个简单的条件 sum() 在你的元组上加起来 如果 x 或/和 y 比那小 1 :

import random

# your code used 15k tuples, your text says 1.5k - adapt the number to your liking
coordinates = [(random.random()*2.0, random.random()*2.0) for _ in range(1500)]

one_lower_1  = sum(1 for x,y in coordinates if x < 1 or  y < 1)
both_lower_1 = sum(1 for x,y in coordinates if x < 1 and y < 1)
x_lower_1    = sum(1 for x,_ in coordinates if x < 1)
y_lower_1    = sum(1 for _,y in coordinates if y < 1)

print(one_lower_1)
print(both_lower_1)
print(x_lower_1)
print(y_lower_1)

产量

1134
383
745
772

这本质上是一个生成器表达式,它只过滤掉与后面的部分匹配的那些对 if .... 从你的生成 coordinates


我选择 sum(1 ... ) 方法,因为这样您就不必创建一个列表来获取 len() …如果只需要元素的计数,然后生成所有元素,则对内存更加友好。


从另一条路 jpp's 评论:

sum(x < 1 or  y < 1 for x,y in coordinates)

因为一笔超过10的钱 True 每人10英镑 True counting as 1 :

print(sum(True for _ in range(10))) # 10
5 年前
回复了 Patrick Artner 创建的主题 » python中的多值变量

您可以使用自定义类:

class Card(object):
    # fancier output
    s = {0:"hearts", 1:"diamonds", 2:"clubs", 3:"spades"}
    r = {i:v for i,v in enumerate( [ "Ace","2","3","4","5","6","7","8",
                                     "9","10","Jack","Queen","King"],1)}
    def __init__(self, suit,rank):
        self.suit = suit
        self.rank = rank

    def __str__(self):
        return "{} of {}".format(Card.r[self.rank],Card.s[self.suit])

    def __repr__(self):
        return str(self)

    def __lt__(self,other):
        return (self.suit,self.rank) < (other.suit, other.rank)


    @classmethod
    def summ_hand(cls,hand):
        return sum ( 10 if card.rank > 10 else card.rank for card in hand)


class Deck(object): 
    def __init__(self):
        self.cards = [Card(suit,rank) for suit in range(4) for rank in range(1,14)]


deck = Deck()

print( deck.cards )

输出:

[Ace of hearts, 2 of hearts, 3 of hearts, 4 of hearts, 5 of hearts, 6 of hearts, 
 7 of hearts, 8 of hearts, 9 of hearts, 10 of hearts, Jack of hearts, Queen of hearts, 
 King of hearts, 
 Ace of diamonds, 2 of diamonds, 3 of diamonds,4 of diamonds,5 of diamonds, 6 of diamonds, 
 7 of diamonds, 8 of diamonds, 9 of diamonds, 10 of diamonds, Jack of diamonds, 
 Queen of diamonds, King of diamonds, 
 Ace of clubs, 2 of clubs, 3 of clubs, 4 of clubs, 5 of clubs, 6 of clubs, 7 of clubs, 
 8 of clubs, 9 of clubs, 10 of clubs, Jack of clubs, Queen of clubs, King of clubs, 
 Ace of spades, 2 of spades, 3 of spades, 4 of spades, 5 of spades, 6 of spades, 
 7 of spades, 8 of spades, 9 of spades, 10 of spades, Jack of spades, Queen of spades, 
 King of spades]

提供 __lq__(self) 允许您排序:

hand = random.choices(deck.cards, k=7)
print(hand)
print(sorted(hand))

print( Card.summ_hand([Card(0,9),Card(0,11),Card(0,13)]))

输出:

# as given by choices
[Ace of hearts, Ace of spades, Queen of diamonds, 9 of spades, 
 King of hearts, Ace of spades, 3 of diamonds]

 # sorted
[Ace of hearts, King of hearts, 3 of diamonds, Queen of diamonds,
 Ace of spades, Ace of spades, 9 of spades]

29  # summ_hand for 9,Queen,King,