在Python中,可以使用lower()方法将字符串转换为小写,从而实现不区分大小写的比较。下面是一个示例代码,该代码将多个列表中的元素与某一列进行比较,如果相同,则将该元素添加到新的列表中。
list1 = ['apple', 'banana', 'ORANGE', 'grape']
list2 = ['GRAPE', 'pear', 'watermelon', 'Apple', 'Pineapple']
list3 = ['cherry', 'orange']
column = ['apple', 'banana', 'orange', 'grape', 'pear', 'pineapple', 'cherry']
result = []
for item in list1 + list2 + list3:
if item.lower() in [col.lower() for col in column]:
result.append(item)
print(result)
此代码将列表中的所有元素转换为小写字母,然后与指定列中的元素进行比较。如果存在相同的元素(不区分大小写),则将其添加到结果列表中。输出结果为:
['apple', 'banana', 'ORANGE', 'grape', 'GRAPE', 'pear', 'Apple', 'Pineapple', 'cherry', 'orange']
上一篇:不区分大小写的单词边界