私信  •  关注

Austin

Austin 最近创建的主题
Austin 最近回复了
5 年前
回复了 Austin 创建的主题 » Python:遍历文件夹并选择以.txt结尾的第一个文件

一种蟒蛇式的方法是 next

next((f for f in file if f.endswith('.txt')), 'file not found')

或者,您可以循环文件并在条件匹配时立即返回:

def find_first_txt_file(files)
    for file in files:
        if file.endswith('.txt'):
            return file
    return 'file not found'
5 年前
回复了 Austin 创建的主题 » 如何在Python中对列表中的字符串执行方法

您可以使用 map :

list(map(lambda x: [x[0].upper()], lst))

:

lst = [['list one'],['list two'],['list...'],['list n']]

print(list(map(lambda x: [x[0].upper()], lst)))
# [['LIST ONE'], ['LIST TWO'], ['LIST...'], ['LIST N']]

这不受限制;我们可以应用任何自定义函数来转换列表中的元素,例如:

list(map(decontracted, lst))
5 年前
回复了 Austin 创建的主题 » 在python中获取输入和接收输出后如何再次请求输入

def check_prime(x):
    for i in range(2,x):  
        if(x % i ==0):      
            print("not Prime")  
            break  
    else :  
        print("Prime")  

x = int(input())
check_prime(x)  # first number
x = int(input())
check_prime(x)  # another number

如果你想要一些 n 要输入的数字,使用无限循环读取 input()

5 年前
回复了 Austin 创建的主题 » 在python 3的另一个dictional中添加带静态键的dictional

添加字典的副本而不是字典本身。

这一行:

dic2[file] = dic1

更改为:

dic2[file] = dic1.copy()
5 年前
回复了 Austin 创建的主题 » 如何从Python中字典的最高值中随机地打破平局?

你可以用 groupby choice :

from itertools import groupby
import random

d = {'banana': 3, 'apple': 12, 'cherry': 1, 'orange': 12}

print(random.choice(max(((k, list(g)) for k, g in groupby(sorted(d, key=d.get), key=d.get)), key=lambda x: x[0])[1]))
5 年前
回复了 Austin 创建的主题 » 如何用这种方法为拆分字符串编写Python正则表达式

您可以使用regex按 r"CA '\w*'" .

import re

re.split(r"CA '\w*'", lines)
# where lines is your input string

如果你的意见 lines 开始/结束于 CA 'xxxx' ,您将得到一个包含上述代码的空字符串,您可以通过以下方式筛选出该字符串:

list(filter(lambda x: x != '', re.split(r"CA '\w*'", lines)))
5 年前
回复了 Austin 创建的主题 » python—事件的出现次数[重复]

使用numpy:

np.sum(a < 4)

或者 sum 发电机上:

sum(num < 4 for num in a)
6 年前
回复了 Austin 创建的主题 » 在python中,在某些字符出现多次之后,如何修剪字符串?

split 然后切片列表以获取所需的 join 以下内容:

s = 'C:\Temp\Test\Documents\Test.doc'

print('\\'.join(s.split('\\')[:3]) + '\\')
# C:\Temp\Test\

请注意 \ (反斜杠)是转义字符。要明确表示反斜杠,请通过在反斜杠之前添加反斜杠来将其强制为反斜杠 \\ ,从而删除反斜杠的特殊含义。

6 年前
回复了 Austin 创建的主题 » 如何在python中使用for循环和lambda函数

你可以使用 filter + lambda ,如果需要使用 兰姆达 :

list(filter(lambda x: x%2 == 0, range(10)))
# [0, 2, 4, 6, 8]

filter() 根据中给定的条件筛选输入元组 兰姆达 .

6 年前
回复了 Austin 创建的主题 » 按关键字长度对词典排序。python 3.6[副本]

字典被认为是无序的,但较新版本的python(3.6+)会记住插入顺序,因此可以执行以下操作:

d = {"aa" : 1, "aaaaaaa": 2, "aaa" : 3, "a": 4}

new_d = {}
for k in sorted(d, key=len, reverse=True):
    new_d[k] = d[k]

print(new_d)
# {'aaaaaaa': 2, 'aaa': 3, 'aa': 1, 'a': 4}
6 年前
回复了 Austin 创建的主题 » python中的字符串regex

你不需要正则表达式。基于分隔符拆分字符串并提取要分配给所需变量的项:

s = "GET /phpmyadmin HTTP/1.1"

method, [localhost, protocol], version = [(x.strip(), y.split(), z) for x, y, z in [s.split('/')]][0]


更具可读性的方式:
for x, y, z in [s.split('/')]:
    method = x.strip()
    localhost, protocol = y.split()
    version = z

因为, phrases = ("Hello There\nHow are you") 不是元组,它仍然是字符串。

如果你这样做了 phrases = ("Hello There\nHow are you",) ,它将成为元组,并且不会像在list case中那样注册换行符。

您可能需要获取元素以测试换行符,如下所示:

phrases = ("Hello There\nHow are you",)
print(phrases[0])

phrases = ["Hello There\nHow are you"]
print(phrases[0])
6 年前
回复了 Austin 创建的主题 » python3函数将列表映射到字典中

你需要 return 从函数开始。

当你这样做的时候 newDict = dict(zip(dict1, dict2)) 在函数中,将创建一个新的字典,其作用域是函数的本地作用域,并且不能在外部访问。

如果您可能在函数之外使用此字典,建议的方法是在函数完成后将新字典返回给调用者。

dict1 = ['aa','bb','cc','dd']
dict2 = ['11','22','33','44']

def map_lists(Dict1, Dict2):
    newDict = dict(zip(dict1, dict2))
    return newDict

newDict = map_lists(dict1, dict2)
print(newDict)


或者,还有一种我不推荐的方法,但仅供参考。
dict1 = ['aa','bb','cc','dd']
dict2 = ['11','22','33','44']

def map_lists(Dict1, Dict2):
    global newDict
    newDict=dict(zip(dict1, dict2))

map_lists(dict1, dict2)
print(newDict)

global 不建议使用,因为它在任何语言中都不是一个好的编程实践。

6 年前
回复了 Austin 创建的主题 » python—从函数调用中去掉括号?

使用 "Q" + str(key) f"Q{str(key)}" (在python 3.6+上)在循环中:

def index_responses(a):
    j = {}
    count = 0
    key = 1
    for y in a:
       j["Q" + str(key)] = a[count]
       count += 1
       key += 1
    return j

print(index_responses(['a', 'b', 'c']))
print(index_responses(['d','d','b','e','e','e','d','a']))

同时请注意,您需要返回 j 而不是 a 它实际上是函数的输入。


获得相同结果的一种更为清洁、更为蟒蛇式的方法是使用字典理解:
def index_responses(a):
    return {f'Q{str(i)}': x for i, x in enumerate(a, 1)}

print(index_responses(['a', 'b', 'c']))
print(index_responses(['d','d','b','e','e','e','d','a']))

# {'Q1': 'a', 'Q2': 'b', 'Q3': 'c'}
# {'Q1': 'd', 'Q2': 'd', 'Q3': 'b', 'Q4': 'e', 'Q5': 'e', 'Q6': 'e', 'Q7': 'd', 'Q8': 'a'}