精华内容
下载资源
问答
  • I need to perform case insensitive string comparisons in python in sets and dictionary keys. Now, to create sets and dict subclasses that are case insensitive proves surprisingly tricky (see: Case ins...

    I need to perform case insensitive string comparisons in python in sets and dictionary keys. Now, to create sets and dict subclasses that are case insensitive proves surprisingly tricky (see: Case insensitive dictionary for ideas, note they all use lower - hey there's even a rejected PEP, albeit its scope is a bit broader). So I went with creating a case insensitive string class (leveraging this answer by @AlexMartelli):

    class CIstr(unicode):

    """Case insensitive with respect to hashes and comparisons string class"""

    #--Hash/Compare

    def __hash__(self):

    return hash(self.lower())

    def __eq__(self, other):

    if isinstance(other, basestring):

    return self.lower() == other.lower()

    return NotImplemented

    def __ne__(self, other): return not (self == other)

    def __lt__(self, other):

    if isinstance(other, basestring):

    return self.lower() < other.lower()

    return NotImplemented

    def __ge__(self, other): return not (self < other)

    def __gt__(self, other):

    if isinstance(other, basestring):

    return self.lower() > other.lower()

    return NotImplemented

    def __le__(self, other): return not (self > other)

    I am fully aware that lower is not really enough to cover all cases of string comparisons in unicode but I am refactoring existing code that used a much clunkier class for string comparisons (memory and speed wise) which anyway used lower() - so I can amend this on a later stage - plus I am on python 2 (as seen by unicode). My questions are:

    did I get the operators right ?

    is this class enough for my purposes, given that I take care to construct keys in dicts and set elements as CIstr instances - my purposes being checking equality, containment, set differences and similar operations in a case insensitive way. Or am I missing something ?

    is it worth it to cache the lower case version of the string (as seen for instance in this ancient python recipe: Case Insensitive Strings). This comment suggests that not - plus I want to have construction as fast as possible and size as small as possible but people seem to include this.

    Python 3 compatibility tips are appreciated !

    Tiny demo:

    d = {CIstr('A'): 1, CIstr('B'): 2}

    print 'a' in d # True

    s = set(d)

    print {'a'} - s # set([])

    解决方案

    In your demo you are using 'a' to look stuff up in your set. It wouldn't work if you tried to use 'A', because 'A' has a different hash. Also 'A' in d.keys() would be true, but 'A' in d would be false. You've essentially created a type that violates the normal contract of all hashes, by claiming to be equal to objects that have different hashes.

    You could combine this answer with the answers about creating specialised dicts, and have a dict that converted any possible key into CIstr before trying to look it up. Then all your CIstr conversions could be hidden away inside the dictionary class.

    E.g.

    class CaseInsensitiveDict(dict):

    def __setitem__(self, key, value):

    super(CaseInsensitiveDict, self).__setitem__(convert_to_cistr(key), value)

    def __getitem__(self, key):

    return super(CaseInsensitiveDict, self).__getitem__(convert_to_cistr(key))

    # __init__, __contains__ etc.

    展开全文
  • I have a list that is generated from multiple lists. This combined list contains names that are generated by end users. Therefore contain similar names, but with different upper/lower case characters....

    I have a list that is generated from multiple lists. This combined list contains names that are generated by end users. Therefore contain similar names, but with different upper/lower case characters.

    I want to filter out the names that contain same characters and just keep the first found in the original list.

    As an example I have the following list:

    L0 = ['A_B Cdef', 'A_B Cdef', 'A_B Cdef', 'A_B CdEF', 'A_B CDEF','a_B CdEF', 'A_b CDEF', 'GG_ooo', 'a1-23456']

    if I run:

    L1 = list(set(L0))

    I get:

    ['a1-23456', 'A_B Cdef', 'A_B CdEF', 'A_B CDEF', 'a_B CdEF', 'A_b CDEF', 'GG_ooo']

    I would like to keep just the first of the names that have same characters.

    So my result is:

    ['a1-23456', 'A_B Cdef', 'GG_ooo']

    If I use .lower(), .upper() I get the list, but the names are lower/upper cased.

    I just want to eliminate "duplicates" without considering case sensitive approach.

    Help greatly appreciated.

    Thanks!

    解决方案

    Use hash instead, I don't think you can accomplish that easily with sets.

    L0 = {value.lower(): value for value in L0[::-1]}.values()

    展开全文
  • I'm new to Python and could really use some help on this. I want to create a function to filter which files I want to open and which months and day specifically. That way, the users need to input whic...

    I'm new to Python and could really use some help on this. I want to create a function to filter which files I want to open and which months and day specifically. That way, the users need to input which city(files) they want to analyze on which particular month or day. However, I want the user to be able to input something that is not case sensitive.

    For example, the user can input 'chicago'/'CHICAGO"/"ChIcAgO" and the it still give you the right output and not the error handling message. Here is the code I use:

    def get_filters ():

    city_options = ['Chicago','New York City','Washington']

    month_options = ['January','February','March','April','May','June','All']

    day_options = ['Monday','Tuesday','Wednesday','Thursday','Friday','Saturday','Sunday','All']

    while True:

    try:

    city = city_options.index(input('\nInsert name of the city to analyze! (Chicago, New York City, Washington)\n'))

    month = month_options.index(input('\nInsert month to filter by or "All" to apply no month filter! (January, February, etc.)\n'))

    day = day_options.index(input('\nInsert day of the week to filter by or "All" to apply no day filter! (Monday, Tuesday, etc.)\n'))

    return city_options[city].lower(), month_options[month].lower(), day_options[day].lower()

    except ValueError:

    print ("Your previous choice is not available. Please try again")

    def load_data (city,month,day):

    #load data file into DataFrame

    df = pd.read_csv(CITY_DATA[city].lower())

    #convert start time column (string) to datetime

    df['Start Time']=pd.to_datetime(df['Start Time'])

    #create new column to extract month and day of the week from start time

    df['Month'] = df['Start Time'].dt.month

    df['Day_of_Week'] = df['Start Time'].dt.weekday_name

    #filter by month if applicable

    if month.lower()!= 'All':

    #use the index of the month list to get corresponding into

    months = ['January', 'February', 'March', 'April', 'May', 'June']

    month = months.index(month) + 1

    #filter by month to create new dataframes

    df = df[df['Month'] == month]

    if day.lower()!= 'All':

    #filter by day_of_week to create new DataFrames

    df =df[df['Day_of_Week'] == day]

    return(df)

    解决方案

    The best way to do so is just take the required input and convert it into the required case.

    Use the inbuilt functions of python

    variable.lower()

    or

    variable.upper()

    展开全文
  • BFPRT(线性查找算法) BFPRT算法解决的问题十分经典,即从某n个元素的序列选出第k(第k)的元素,通过巧妙的分 析,BFPRT可以保证在最坏情况下仍为线性时间复杂度.该算法的思想与快速排序思想相似,当然,为使得算法...

    &lbrack;转载&rsqb;jQuery诞生记-原理与机制

    by zhangxinxu from http://www.zhangxinxu.com本文地址:http://www.zhangxinxu.com/wordpress/?p=3520 一.看似偶然的 ...

    BFPRT&lpar;线性查找算法&rpar;

    BFPRT算法解决的问题十分经典,即从某n个元素的序列中选出第k大(第k小)的元素,通过巧妙的分 析,BFPRT可以保证在最坏情况下仍为线性时间复杂度.该算法的思想与快速排序思想相似,当然,为使得算法 ...

    老外写的在桌面添加快捷方式(DELPHI XE5 ANDROID)

    UsesAndroidapi.JNI.GraphicsContentViewText, FMX.Helpers.Android,Androidapi.JNI.JavaTypes, FMX.Platfo ...

    【转】使用Memcached提高&period;NET应用程序的性能

    在应用程序运行的过程中总会有一些经常需要访问并且变化不频繁的数据,如果每次获取这些数据都需要从数据库或者外部文件系统中去读取,性能肯定会受到影响,所以通常的做法就是将这部分数据缓存起来,只要数据没有发 ...

    Redhat 6 配置CentOS yum source

    由于最近曝出linux的bash漏洞,想更新下bash,于是 想到了配置CentOS yum source. 测试bash漏洞的命令: env x='() { :;}; echo "Your ...

    Mesos&plus;Zookeeper&plus;Marathon&plus;Docker分布式集群管理最佳实践

    参考赵班长的unixhot以及马亮blog 笔者QQ:572891887 Linux架构交流群:471443208 1.1Mesos简介 Mesos是Apache下的开源分布式资源管理框架,它被称为分 ...

    「FHQ Treap」学习笔记

    话说天下大事,就像fhq treap —— 分久必合,合久必分 简单讲一讲.非旋treap主要依靠分裂和合并来实现操作.(递归,不维护fa不维护cnt) 合并的前提是两棵树的权值满足一边的最大的比另一 ...

    iBATIS 传MAP处理方式(value是list的方式)

    1.前提条件 参数是map结构的数据 key:String 类型 value:list 集合 2.处理方式 遍历集合一般常规的方式使用iterate,这里也不例外了,如下

    性能调优6:Spool 假脱机调优

    SQL Server的Spool(假脱机)操作符,用于把前一个操作符处理的数据(又称作中间结果集)存储到一个隐藏的临时结构中,以便在执行过程中重用这些数据.这个临时结构都创建在tempdb中,通常的结 ...

    hibernate06--参数的绑定

    创建Dept实体类 以及 对应的 Dept.hbm.xml文件 /** * @author 小豆腐 * *部门的实体类 */ public class Dept { private Integer d ...

    展开全文
  • 【判断题】Python 是一种解释型、面向对象、动态数据类型的高级程序设计语言。【判断题】当if有多个条件时可使用括号()来区分判断的先后顺序。【单选题】用加热驱除水分法测定 CaSO 4 · 1/2H 2 O 结晶水的含量时 ...
  • 【判断题】Python变量不区分大小写 【判断题】生产管理级(L3)主要依赖于利用数据库系统。 【判断题】在读取现场轧机控制系统生成的.txt格式记录文件时,常用Pandas模块,用于读取文件的函数为read_txt。 【判断题】...
  • python变量名区分大小写

    千次阅读 2021-01-13 19:32:57
    Python的变量名是区分大小写的,例如:name和Name就是两个变量名,而非相同变量。变量(variable)是学习python初始时,就会接触到的一个新的知识点,也是一个需要熟知的概念。python是一种动态类型语言,在赋值的执行...
  • python代码区分大小写

    千次阅读 2021-01-13 13:03:21
    python代码区分大小写python中区分大小写的,不管是变量、函数、还是类,都要严格的区分大小写。例如,page和Page是两个不同的变量,name和Name也是完全不同的两个变量。如果小心混淆了变量的名,程序会报错...
  • 最近在用Python处理一些数据,数据需要存储到MySQL数据库,采用MySQLdb来进行数据库的操作,但是被一个问题困扰了很久。在打开数据库的时候MySQLdb.connect(self.host, self.user, self.password, self.database, ...
  • python变量名不区分大小写

    千次阅读 2021-01-13 11:34:41
    形象地看,变量就像一个个容器,用于“盛装”程序的数据。除了变量,还有常量,它也能用来“盛装”数据,它们的区别是,常量一旦保存某个数据之后,该数据就能发生改变;但变量保存的数据则可以多次发生改变,...
  • 有时候,我们需要检测一个元素是否已经存在列表,并且不区分大小写,如:列表已有元素Mary,那我们想认为MARY也已经被占用。这个例子在实际编程会用到很多,比如保证网站注册用户独一无二、邮件姓名独一无二等等...
  • Python变量名区分大小写,所以student和Student不是同一个变量。答:对老子说:“道法自然。”(《道德经》第二十五章)其中“自然”的意思是( )答:自然而然内蒙古国家级历史文化名城有答:呼和浩特中国大学MOOC: ...
  • Python变量名是不是区分大小写的发布时间:2020-11-10 14:13:23来源:亿速云阅读:95作者:小新Python变量名是不是区分大小写的?这个问题可能是我们日常学习或工作经常见到的。希望通过这个问题能让你收获颇深。...
  • python区分大小写

    千次阅读 2021-01-13 13:03:30
    python区分大小写吗发布时间:2020-09-21 14:19:55来源:亿速云阅读:84作者:Leahpython区分大小写吗?很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习...
  • 代码如下:#encoding=utf-8print '中国'#对字符串列表排序,不区分大小写print '--DSU方法'def case_insensitive_sort(sort_strlist):auxiliary_list = [(x.lower(),x) for x in sort_strlist] #decorateauxiliary_...
  • Python中的代码是区分大小写的,无论是变量、函数还是类,都需要严格的区分大小写。比如说:page和Page是两个不同的变量,name和Name也是完全不同的两个变量,如果小心混淆了变量的名,程序运行时就会报错。举例...
  • 欢迎关注微信公众号【计算机视觉联盟】获取更多前沿AI、CV资讯 有时候,我们需要检测一个元素是否已经存在列表,并且不区分大小写,如:列表已有元素Mary,那我们想认为MARY也已经被占用。这个例子在实际编程会...
  • 此解决方案使用两个正则表达式。...在 函数首先尝试将正则表达式与输入文本匹配。如果匹配,则使用第二个regex除去最外层HTML...还请注意,此解决方案处理具有包含>字符的属性的HTML标记(但这种情况应该非常罕见)。在
  • python re.sub 大小写

    2020-12-31 04:08:45
    答:列出一组数据,经常用在 for ... 答:可以使用 re 模块的 sub()函数或者 subn()函数......('nice','good') good day #s 本身改变,但会返回一个字符串:output: #sub import re s='cat1 cat2 cat3 in the xxx' r...
  • python变量名要不要区分大小写发布时间:2020-11-23 11:40:34来源:亿速云阅读:106作者:小新小编给大家分享一下python变量名要不要区分大小写,相信大部分人都还怎么了解,因此分享这篇文章给大家参考一下,希望...
  • 另外,我使用re.IGNORECASE来匹配大小写字符串。但是,当我执行搜索(例如“locality”)时,我能够获得“localit”、“local”、“local”等的字符串匹配。我想和确切的词匹配(如“地点”)。在另外,如果字符串字符...
  • 请将脚本保存到一个文件,例如search-word.py,然后运行:$ python -i search-word.py 它显示Python提示符:>>> 您可以尝试单个表达式来查看它们的作用,例如:>>> zip(repeat('a'), [1,2,3]) [('a', 1), ('a', 2)...
  • 小智..75这是一个基准测试,显示使用str.lower比接受的答案的.../usr/bin/env python2.7import randomimport timeitfrom ctypes import *libc = CDLL('libc.dylib') # change to 'libc.so.6' on linuxwith open('/u...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 98,913
精华内容 39,565
关键字:

python中不区分大小写

python 订阅