了解集合比较 [英] Understanding set comparison

查看:60
本文介绍了了解集合比较的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以,我的问题是了解列表之间的比较。

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")

我无法理解的< =。它会比较设置的唯一列表中的字母吗?还是只比较长度?因为如果没有加入,我也会获得Space。
如果只有 set(str.lower())不能对每个字母进行排序,< =相比如何?

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!

推荐答案

运算符< = 设置,检查LHS上的操作数是否是RHS上的操作数的子集。

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

更详细地说:

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

在旁注中,请小心不要使用 str 作为名称,以免使内置的 str 在您的函数中无法使用。

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

这篇关于了解集合比较的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆