dylan-oo 发表于 2020-12-9 20:06:12

元组比较

>>> temp1 = ('水逆','快乐','爱情')
>>> temp2 = ('哟欧青','辣子','玫瑰','眼里','扶苏')
>>> temp3 = temp1 + temp2
>>> temp3
('水逆', '快乐', '爱情', '哟欧青', '辣子', '玫瑰', '眼里', '扶苏')
>>> temp2<temp3
True
>>> temp1>temp2
True
>>> temp3<temp2
False


求助各路大神,为何 temp2<temp3为
True,而temp1>temp2也是
True?元组之间的比较遵循什么规则?

昨非 发表于 2020-12-9 20:11:52

参考:https://blog.csdn.net/maizousidemao/article/details/106323920?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522160751574619726891139053%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=160751574619726891139053&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_v2~rank_v29-1-106323920.pc_search_result_cache&utm_term=%E5%85%83%E7%BB%84%E5%A4%A7%E5%B0%8F%E6%AF%94%E8%BE%83&spm=1018.2118.3001.4449


补充:字符串的大小比较一次比较各个字符的编码大小(中文字符比较特殊)。参考https://blog.csdn.net/weixin_37985288/article/details/93968818?ops_request_misc=%257B%2522request%255Fid%2522%253A%2522160751586719724847137432%2522%252C%2522scm%2522%253A%252220140713.130102334.pc%255Fall.%2522%257D&request_id=160751586719724847137432&biz_id=0&utm_medium=distribute.pc_search_result.none-task-blog-2~all~first_rank_v2~rank_v29-4-93968818.pc_search_result_cache&utm_term=%E6%B1%89%E5%AD%97%E6%80%8E%E4%B9%88%E6%AF%94%E8%BE%83%E5%A4%A7%E5%B0%8F&spm=1018.2118.3001.4449

笨鸟学飞 发表于 2020-12-9 23:02:42

1、查阅文档
https://fishc.com.cn/forum.php?mod=viewthread&tid=48793&extra=page%3D1%26filter%3Dtypeid%26typeid%3D403
__lt__(self, other)        定义小于号的行为:x < y 调用 x.__lt__(y)
__gt__(self, other)        定义大于号的行为:x > y 调用 x.__gt__(y)
2、查看帮助文档
>>> help(tuple)# 可以发现,元祖也是有上述的比较运算符方法的

具体怎么定义的呢?以下是源代码,有兴趣可以去看看(貌似并没有什么卵用)
class tuple(Sequence, Generic):
    def __new__(cls: Type, iterable: Iterable = ...) -> _T: ...
    def __init__(self, iterable: Iterable = ...): ...
    def __len__(self) -> int: ...
    def __contains__(self, x: object) -> bool: ...
    @overload
    def __getitem__(self, x: int) -> _T_co: ...
    @overload
    def __getitem__(self, x: slice) -> Tuple: ...
    def __iter__(self) -> Iterator: ...
    def __lt__(self, x: Tuple) -> bool: ...
    def __le__(self, x: Tuple) -> bool: ...
    def __gt__(self, x: Tuple) -> bool: ...
    def __ge__(self, x: Tuple) -> bool: ...
    @overload
    def __add__(self, x: Tuple) -> Tuple: ...
    @overload
    def __add__(self, x: Tuple) -> Tuple: ...
    def __mul__(self, n: int) -> Tuple: ...
    def __rmul__(self, n: int) -> Tuple: ...
    def count(self, x: Any) -> int: ...
    if sys.version_info >= (3, 5):
      def index(self, x: Any, start: int = ..., end: int = ...) -> int: ...
    else:
      def index(self, x: Any) -> int: ...

dylan-oo 发表于 2020-12-10 23:07:11

昨非 发表于 2020-12-9 20:11
参考:https://blog.csdn.net/maizousidemao/article/details/106323920?ops_request_misc=%257B%2522reque ...

谢谢大佬,我好好消化一下。

昨非 发表于 2020-12-10 23:10:48

dylan-oo 发表于 2020-12-10 23:07
谢谢大佬,我好好消化一下。

主要看怎么用了,
一般字符串比较英文比较多
中文字符大小比较确实少见

理解了记得给个最佳答案哈
页: [1]
查看完整版本: 元组比较