繁体   English   中英

Python 中的嵌套循环有两个列表

[英]Nested loops in Python with two list

为什么我的循环不返回第一个值? 如果此文本存在于我的值中,我想替换特定文本,但如果不存在,我想获得初始含义。 在最后一个值中,我得到了我需要的值,但首先值我的代码未命中。

    p = ["Adams","Tonny","Darjus FC", "Marcus FC", "Jessie AFC", "John CF", "Miler 
    SV","Redgard"]
    o = [' FC'," CF"," SSV"," SV"," CM", " AFC"]
    for i, j in itertools.product(p, o):
        if j in i:
            name = i.replace(f"{j}","")
            print(name)
        elif j not in i:
            pass        
    print(i)

我懂了:

    Darjus
    Marcus
    Jessie
    John
    Miler
    Redgard

但我想要这个:

    Adams
    Tonny
    Darjus
    Marcus
    Jessie
    John
    Miler
    Redgard

product() 的使用将使解决这个问题变得比需要的困难得多。 使用嵌套循环会更容易。

p = ["Adams", "Tonny", "Darjus FC", "Marcus FC",
     "Jessie AFC", "John CF", "Miler SV", "Redgard"]
o = [' FC', " CF", " SSV", " SV", " CM", " AFC"]

for i in p:
    # Store name, for if no match found
    name = i
    for j in o:
        if j in i:
            # Reformat name if match
            name = i.replace(j, "")
    print(name)

如果您想将名称存储在列表中,这是一种方法:

p = ['Adams', 'Tonny', 'Darjus FC', 'Marcus FC', 'Jessie AFC', 'John CF', 'Miler SV', 'Redgard']
o = ['FC', 'CF', 'SSV', 'SV', 'CM', 'AFC']
result = []

for name in p:
    if name.split()[-1] in o:
        result.append(name.split()[0])
    else:
        result.append(name)
print(result)

['Adams', 'Tonny', 'Darjus', 'Marcus', 'Jessie', 'John', 'Miler', 'Redgard']

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM