问答详情
源自:8-2 Python读取set元素

请问lower()的引用是这样的吗?这段要怎么改才能运行正确呀

请问lower()的引用是这样的吗?这段要怎么改才能运行正确呀_

names = ['Alice', 'Bob', 'Candy', 'David', 'Ellena']

name_set = set(names)

if 'bob' in name_set:

    print('True')

name_lower=name_set.lower()

print(name_lower)

if 'bob' in name_lower:

    print('yep')

else:

    print('None')


——————————————————————————

Traceback (most recent call last):
  File "index.py", line 6, in 
    name_lower=name_set.lower()
AttributeError: 'set' object has no attribute 'lower'


提问者:真厉害 2021-07-19 23:12

个回答

  • 慕后端4297166
    2021-07-20 22:49:57
    已采纳

    names = ['Alice', 'Bob', 'Candy', 'David', 'Ellena']


    new_names=[]

    for i in names:

      name_lower=i.lower()

      new_names.append(name_lower)

    # print(new_names)


    if 'bob' in new_names:

        print('yep')

    else:

        print('None')


  • qq_慕婉清6326688
    2022-06-27 10:21:47

    names = ['Alice', 'Bob', 'Candy', 'David', 'Ellena']

    name_set = set(names)

    #print('BOB' in name_set)

    extend_set = set([])

    for i in name_set:

    extend_set.add(i)

    name_lower = i.lower()

    extend_set.add(name_lower)

    print(extend_set)

    name = 'Bob'

    if name in extend_set:

    print('yes')

    else:

    print('no')


  • 慕瓜9057676
    2022-02-12 15:04:16

    names = ['Alice', 'Bob', 'Candy', 'David', 'Ellena']
    for i in names:
        name_lower=i.lower()
        names.append(name_lower)
        if len(names) > 10:
            break
        print(names)
    if 'bob' in names:
        print('yep')
    else:
        print('None')


  • Ruissedella
    2021-07-30 14:08:02

    http://img3.mukewang.com/610395650001d9e905890346.jpg

    试着运行了一下上面这位哥们儿的代码,发现这样就没有原来的首字母大写的名字了。所以试着改了一下在for循环里再加一个嵌套的for,将原来的名字也扫进来,个人感觉会更好些!

    names = ['Alice', 'Bob', 'Candy', 'David', 'Ellena']

    name_extend = [ ]

    for each in names:

        name_lower = each.lower( )

        name_extend.append(name_lower)

        for each in names:

            if each not in name_extend:

            name_extend.append(each)


    #print(name_extend)

    之后用in/not in来进行检测就可以了