如何将名称列表转换为缩写

发布于 2025-02-07 09:41:34 字数 466 浏览 2 评论 0原文

我有一个只需转向缩写的名称列表,因此['姓氏,名称']将为ns。这是我到目前为止所做的:

list_names = [['Johnson, Sarah'],['Hill, Becky'],['Smith, John']]
for name in list_names:
    for name_string in name:
        split = name_string.split(", ")
        join = " ".join(split)
        initials = ""
        for n in split:
            initials += n[0].upper()
            print(initials)

我认为这是我出错的最后一步,任何帮助都非常感谢

:我现在已经修复了错字,名称最初是在numpy.ndarray中。进入名为list_names的列表

I have a list of names that I need to turn to initials only, so for example ['Surname, Name'] would be NS. This is what I have done so far:

list_names = [['Johnson, Sarah'],['Hill, Becky'],['Smith, John']]
for name in list_names:
    for name_string in name:
        split = name_string.split(", ")
        join = " ".join(split)
        initials = ""
        for n in split:
            initials += n[0].upper()
            print(initials)

I think it's one of the last steps where I'm going wrong, any help is much appreciated

Edit: I have fixed the typo now, the names were originally in numpy.ndarray which I then turned into the list called list_names

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

酷到爆炸 2025-02-14 09:41:34

为了拆分,我已经使用了.split(“”,“,”)逗号加上空间,就像输入列表中一样。

list_names = [['Johnson, Sarah'],['Hill, Becky'],['Smith, John']]
for name in list_names:
    surname,name=name[0].split(', ')
    initials=name[0]+surname[0]
    initials=initials.upper()
    print(initials)

我认为您希望以这种方式输出:

SJ
BH
JS

For splitting i have used .split(", ") comma plus space as is it included in the input list.

list_names = [['Johnson, Sarah'],['Hill, Becky'],['Smith, John']]
for name in list_names:
    surname,name=name[0].split(', ')
    initials=name[0]+surname[0]
    initials=initials.upper()
    print(initials)

I think you want output in this way:

SJ
BH
JS
爱格式化 2025-02-14 09:41:34

您可以通过列表理解

list_names = [['Johnson, Sarah'],['Hill, Becky'],['Smith, John']]
[f"{i[0].split(',')[1][1]}{i[0].split(',')[0][0]}" for i in list_names]

结果来完成:

['SJ', 'BH', 'JS']

You can do it with a list comprehension

list_names = [['Johnson, Sarah'],['Hill, Becky'],['Smith, John']]
[f"{i[0].split(',')[1][1]}{i[0].split(',')[0][0]}" for i in list_names]

result:

['SJ', 'BH', 'JS']
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文