Understanding set comparison

旧巷老猫 提交于 2019-11-27 08:51:08

问题


So, my problem is to understand comparison between lists.

I had a homework to compare if some string has all the letters from the alphabet, so i did this:

import string


def ispangram(str):

  letters = ''.join(str.split()).lower()
  unique_letters = set(letters)
  sorted_list = list(sorted(unique_letters))
  str_alphabet = ''.join(sorted_list)

  alphabet = string.ascii_lowercase

  if str_alphabet == alphabet:
      print(True)
  else:
      print(False)


ispangram("The quick brown fox jumps over the lazy dog")

Ok, i got True, thats fine. But the other way for the answer is:

import string


def ispangram(str):
  alphabet = string.ascii_lowercase
  alphaset = set(alphabet)

  return alphaset <= set(str.lower()):


ispangram("The quick brown fox jumps over the lazy dog")

So this "<=" that i cant understand. It compares letter by letter in the set unique list? Or it just compare the lenght of it? Because without joining i get Space ' ' too. And how does "<=" compare if only "set(str.lower())" does not sort every letter?

Hope somebody could help me, thanks a lot!


回答1:


The operator <= for sets, checks if the operand on the LHS is a subset of the one on the RHS.

More verbosely:

alphaset.issubset(my_str.lower()) # issubset takes any iterable

On a side note, be careful to not use str as a name to not make the builtin str unusable within your function.



来源:https://stackoverflow.com/questions/42788375/understanding-set-comparison

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!