私信  •  关注

Freddy Mcloughlan

Freddy Mcloughlan 最近创建的主题
Freddy Mcloughlan 最近回复了
3 年前
回复了 Freddy Mcloughlan 创建的主题 » Python数组排序文件夹名称

使用 sorted() 返回已排序对象的副本。你只是把整理好的副本退回,什么也不做。你需要 .sort() 来修改字符串。

您还需要创建一个键函数来指定您是按末尾的数字排序,而不是按字母数字排序。

import re

def order(x):
    try:
        # This searches and returns the first number found in the folder name
        return int(re.search("\d+", x).group(0))
    except (ValueError, TypeError, AttributeError):
        return 0


list1.sort(key=order)
output  ['New folder', 'New folder 1', 'New folder 2', 'New folder 10']

编辑:

为了解释信件:

list1 = ["Abc 1", "Abc 10", "Abc", "Test", "Test 20", "New folder",
         "New folder 1", "New folder 10", "New folder 2"]


def order(x):
    try:
        return x + re.search("\d+", x).group(0)
    except (ValueError, TypeError, AttributeError):
        return x


list1.sort(key=list)
output  ['Abc', 'Abc 1', 'Abc 10', 'New folder', 'New folder 1', 'New folder 10', 'New folder 2', 'Test', 'Test 20']

还有你的另一个问题。在拥有所有文件夹名称后进行排序,而不是在添加它们时进行排序。

3 年前
回复了 Freddy Mcloughlan 创建的主题 » python中如何按某个重复索引拆分列表

可以将嵌套生成器(列表)用于一行程序:

base = [97, 98, 99, 100, 101, 102, 103, 104,
        105, 106, 107, 108, 109, 110, 111, 112]

y = ["".join((chr(k) for k in j))for j in (base[i:i+4]for i in range(0, len(base), 4))]
>>> y
['abcd', 'efgh', 'ijkl', 'mnop']

如果你正在使用 floats (小数)通过以下方式转换为int:

y = ["".join((chr(int(k)) for k in j))for j in (base[i:i+4]for i in range(0, len(base), 4))]
#                 ^^^
3 年前
回复了 Freddy Mcloughlan 创建的主题 » 替换python中在我的代码中不起作用的函数

使用 i.replace(a, "") 只返回替换的字符串。您需要将结果重新分配到列表中。要做到这一点,您需要编辑 lst 带索引 i :

def rmv_spc(lst, a):
    a = str(a)
    for i in range(len(lst)):
        x = str(lst[i])
        lst[i] = x.replace(a, "")
    return lst

更好的方法是使用列表理解:

def rmv_spc(lst, a):
    a = str(a)
    return [str(x).replace(a, "") for x in lst]

这就是为什么 replace 作品:

# Assign x
>>> x = 'abc'
>>> x
'abc'
# Replace 'a' with nothing
>>> x.replace('a','')
'bc'
# That is the result that we wanted, but x is still the same
>>> x
'abc'
# So we need to say that x = that result
>>> x = x.replace('a','')
>>> x
'bc'
3 年前
回复了 Freddy Mcloughlan 创建的主题 » python中ldap返回值的字符串拆分

个人名单

当你定义 x 作为:

x = [('CN=b12345,OU=Accounts,DC=mydomain,DC=com',
      {'Fname': ['Jose, Movi'],
       'location': [b'London'],
       'mail': [b'jose.movi@google.com'],
       'title': [b'Sales -Exec -Retail']})]

你可以在一张纸上打印 key value 方式:

for k, v in x[0][1].items():
    try:
        print(f"{k.title()}: {', '.join(a.decode('utf-8') for a in v)}")
    except (UnicodeEncodeError, AttributeError):
        # If you try to decode a regular string
        print(f"{k.title()}: {', '.join(v)}")

输出

Fname: Jose, Movi
Location: London
Mail: jose.movi@google.com
Title: Sales -Exec -Retail

或者为每个 钥匙 :

def printer(k, v):
    try:
        print(f"{k.title()}: {', '.join(a.decode('utf-8') for a in v)}")
    except (UnicodeEncodeError, AttributeError):
        # If you try to decode a regular string
        print(f"{k.title()}: {', '.join(v)}")


for k, v in x[0][1].items():
    if k == "Fname":
        printer("DisplayName", v)
    elif k == "mail":
        printer("Email", v)
    elif k == "title":
        printer("Designation", v)
    else:
        printer(k, v)

产出:

Displayname: Jose, Movi
Location: London
Email: jose.movi@google.com
Designation: Sales -Exec -Retail

如果你正在使用 >= Python3.10 你可以用 match 自定义标题的声明:

for k, v in x[0][1].items():
    match k:
        case "Fname":
            printer("DisplayName", v)
        case "mail":
            printer("Email", v)
        case "title":
            printer("Designation", v)
        case _:
            # Default case
            printer(k, v)

所有列表

当你定义 十、 作为:

x = [[('CN=b12345,OU=Accounts,DC=mydomain,DC=com',
       {'Fname': ['Jose, Movi'],
        'location': [b'London'],
        'mail': [b'jose.movi@google.com'],
        'title': [b'Sales -Exec -Retail']})],
     [('CN=h12345,OU=Accounts,DC=mydomain,DC=com',
      {'Fname': ['Lorraine, Moses'],
       'location': [b'Boston'],
       'mail': [b'Lorraine.Moses@google.com'],
       'title': [b'Sales -ExecIII -Retail']})],
     [('CN=o12345,OU=Accounts,DC=mydomain,DC=com',
      {'Fname': ['Andy, Cameron'],
       'location': [b'NewYork'],
       'mail': [b'Andy.Cameron@google.com'],
       'title': [b'Customer Support II - Fixed']})]]

你可以编辑你的例子,使之成为另一个例子 for 循环 i :

for i in x:
    for k, v in i[0][1].items():
    # Rest of method goes here

如果严格使用单元素列表,则可以更改 ', '.join(a.decode('utf-8') for a in v) v.decode('utf-8') ', '.join(v) v

3 年前
回复了 Freddy Mcloughlan 创建的主题 » Python函数找不到全局变量

你必须使用 global 访问全局变量。代码中还有一些错误,我已经修复并注释了这些错误:

def b0_b1_calc():
    # Use global to access global variables
    global b1

    # sum() summates a list
    x_sum = sum(x_data)
    y_sum = sum(y_data)

    # This was the wrong way around
    x_mean = round(x_sum / len(x_data))
    y_mean = round(y_sum / len(y_data))

    x_list = []  # could also be [i - x_mean for i in x_data]
    y_list = []  # could also be [i - y_mean for i in x_data]

    for i in x_data:
        x_list.append(i - x_mean)
        y_list.append(i - y_mean)

    # could also be [(x_list[i] - x_mean) ** 2 for i in x_list]
    x_minus_x_squared = []

    for i in x_list:
        x_minus_x_squared.append((x_list[i] - x_mean) ** 2)

    x_sum = sum(x_minus_x_squared)
    x_y = []

    for i in x_data:
        # could be simplified to [np.array(y_list) * np.array(x_list) for i in x_data]
        # use np.array for vectorial array multiplication
        x_y.append(np.array(y_list) * np.array(x_list))
    
    x_y = sum(x_y)
    b1 = x_y / x_sum


b0_b1_calc()

绕开环球旅行的首选方式是打电话 return :

def b0_b1_calc():
    # ... code here
    return b1

b1 = b0_b1_calc()
3 年前
回复了 Freddy Mcloughlan 创建的主题 » Python-列表的平方根

也许是这个?

# Use this import for all examples
from math import sqrt

old = [1,2]
new = [sqrt(x) for x in old]

函数形式

def sqrt_list(old):
    return [sqrt(x) for x in old]

def sqrt_list(old):
    new_list = []

    for i in old:
        new_list.append(sqrt(i))

    return new_list

哪里:

print(sqrt_list([11, 22, 33]))

产出:

[3.3166247903554, 4.69041575982343, 5.744562646538029]