cha*_*asm 4 python string list
我正在寻找一些帮助,比较2个Python列表,list1和list2的顺序,以检测list2何时出现故障.
a,b,c,d,e,f,g,h,i,j.这是"正确的"订单.a,b,f,d,e,g,c,h,i,j或 a,b,c,d,e)我正在寻找一种有效的方法,通过将它与list1进行比较来检测list2何时是我们的订单.
例如,如果列表2是a,c,d,e,g,i应该返回true(因为字符串是按顺序)
同时,如果列表2是a,d,b,c,e应该返回false(如出现不按顺序串d)
首先,让我们来定义list1:
>>> list1='a,b,c,d,e,f,g,h,i,j'.split(',')
>>> list1
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']
Run Code Online (Sandbox Code Playgroud)
虽然您list1恰好按字母顺序排列,但我们不会假设这一点.此代码无论如何都有效
现在,让我们创建一个list2无序的:
>>> list2 = 'a,b,f,d,e,g,c,h,i,j'.split(',')
>>> list2
['a', 'b', 'f', 'd', 'e', 'g', 'c', 'h', 'i', 'j']
Run Code Online (Sandbox Code Playgroud)
以下是如何测试是否list2出现故障:
>>> list2 == sorted(list2, key=lambda c: list1.index(c))
False
Run Code Online (Sandbox Code Playgroud)
False 意味着无序.
这是一个有序的例子:
>>> list2 = 'a,b,d,e'.split(',')
>>> list2 == sorted(list2, key=lambda c: list1.index(c))
True
Run Code Online (Sandbox Code Playgroud)
True 意味着有序.
让我们考虑一个list2不具有以下元素的元素list1:
>>> list2 = 'a,b,d,d,e,z'.split(',')
Run Code Online (Sandbox Code Playgroud)
要忽略不需要的元素,让我们创建list2b:
>>> list2b = [c for c in list2 if c in list1]
Run Code Online (Sandbox Code Playgroud)
然后我们可以像以前一样测试:
>>> list2b == sorted(list2b, key=lambda c: list1.index(c))
True
Run Code Online (Sandbox Code Playgroud)
sorted>>> list2b = ['a', 'b', 'd', 'd', 'e']
>>> indices = [list1.index(c) for c in list2b]
>>> all(c <= indices[i+1] for i, c in enumerate(indices[:-1]))
True
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
118 次 |
| 最近记录: |