names_to_bands.setdefault(name,[]).append('Wings')



  • The function in the cycle returns the name and name of the group Why would she add the name of the group to the existing name when retaking?

    band1_names = ['John', 'George', 'Paul', 'Ringo']
    band2_names = ['Paul']
    names_to_bands = {}
    for name in band1_names:
        names_to_bands.setdefault(name,['Beatles'])
    for name in band2_names:
        names_to_bands.setdefault(name,[]).append('Wings')
    print(names_to_bands['Paul'])
    

    ['Beatles', 'Wings']

    P/S/ names_to_bands = {'John': ['Beatles'], 'George': ['Beatles'], 'Paul':



  • You're using it wrong. setdefault combined with append♪ What's important is the challenge of this method and challenge. append independent.

    setdefault returns value dict By the key. get or []and if there is no such key adds dict the value for the key given by the second parameter. And most importantly, append I'm calling for a list anyway.

    It means this line:

    names_to_bands.setdefault(name,[]).append('Wings')
    

    It works as follows:

    1. if name Total names_to_bands No, it's equivalent. names_to_bands[name] = ['Wings']
    2. if name Total names_to_bands Yes, it is. names_to_bands[name].append('Wings')

    I mean, with a re-call, you'll add a duplicate that you're watching.

    What you need to do is:

    bands = names_to_bands.setdefault(name,[])
    if 'Wings' not in bands:
        bands.append('Wings')
    

    or use it. set For the list:

    names_to_bands.setdefault(name, set()).add('Wings')
    

Log in to reply
 

Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2