Python在一组字母上创建一个范围

2024-04-25 18:55:48 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名字列表,我需要把所有以a到L开头的姓氏写进一个文件,把其他以M到Z开头的姓氏写进另一个文件。有什么想法吗?谢谢。你知道吗

if surname[0] in range(A, L):
    print("a to l")
elif surname[0] in range(M, Z):
    print("m to z")

Tags: 文件toin列表ifrangesurname名字
3条回答

因为您要测试每个姓氏的首字母,所以string方法startswith解释了代码的内容。你知道吗

import string
a_to_l = tuple (c for c in string.ascii_uppercase if c <= 'L')

surnames = ['Jacobson', 'Johnson', 'Williams', 'Abrahams', 'Putin']

with open('a_to_l.txt','w') as file_a_to_l, open('m_to_z.txt','w') as file_m_to_z:
    for surname in surnames:
        if surname.startswith(a_to_l):
            print(surname, file=file_a_to_l)
        else:
            print(surname, file=file_m_to_z)

格雷格。使用您在问题中提供的代码,我将更改以下内容:

surnames = ['Jacobson', 'Johnson', 'Williams', 'Abrahams', 'Putin', 'Trump', 'Obama', 'Nixon']
with open('a_to_l_names.txt', 'w') as a_to_l, open('m_to_z.txt', 'w') as m_to_z:
    for surname in surnames:
        if ord(surname[0]) in range(ord('A'), ord('L') + 1):
            print("a to l")
            a_to_l.write(surname)
        else:
            print("m to z")
            m_to_z.write(surname)

附加的elif条件是多余的。除非你希望名字不是以大写字母开头。必须使用ord()获取字母的Unicode代码来检查范围。你知道吗

正因为我喜欢尽可能地提供regex解决方案,即使你没有回复这篇文章,这里有另一种方法你可以使用。你知道吗

import re
a_to_l_pattern = r'^[a-lA-L]{1}'
with open('a_to_l_names.txt', 'w') as a_to_l, open('m_to_z.txt', 'w') as m_to_z:
    for surname in surnames:
        if re.search(a_to_l_pattern, surname):
            print("a to l")
            a_to_l.write(surname)
        else:
            print("m to z")
            m_to_z.write(surname)

下面是一个小例子:

f = [i.strip('\n').split() for i in open('filename.txt')]

import string

letters = string.ascii_uppercase
group1 = letters[:12]

group2 = letters[12:]

first_group = [i[1] for i in f for b in group1 if i[1][0] == b] #contains list of surnames starting with letters in group1

second_group = [i[1] for i in f for b in group2 if i[1][0] == b] #contains list of surnames starting with letters in group2

file1 = open('other_file.txt', 'w')
file2 = open('other_file1.txt', 'w')

for a, b in zip(first_group, second_group):
    file1.write(a+"\n")
    file2.write(b+"\n")

file1.close()
file2.close()

相关问题 更多 >