Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/301.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/powershell/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python交集不一致的出现顺序_Python - Fatal编程技术网

Python交集不一致的出现顺序

Python交集不一致的出现顺序,python,Python,我试图得到一个字符串的日期时间分隔符列表,其顺序与它们在字符串中出现的顺序相同 假设我有以下日期时间:2015-03-2512:22:21;我打算从set().intersection获得的输出是这样的列表:['-',''] 问题是它反过来了。这似乎是随机的。请看一下以下输出: [IN]: list(set('/|.-T ').intersection('2015-03-25 12:22:21')) [OUT]: [' ', '-'] 现在,这一点是正确的: [IN]: list(set('/

我试图得到一个字符串的日期时间分隔符列表,其顺序与它们在字符串中出现的顺序相同

假设我有以下日期时间:
2015-03-2512:22:21
;我打算从
set().intersection
获得的输出是这样的列表:
['-','']

问题是它反过来了。这似乎是随机的。请看一下以下输出:

[IN]: list(set('/|.-T ').intersection('2015-03-25 12:22:21'))
[OUT]: [' ', '-']
现在,这一点是正确的:

[IN]: list(set('/|.-T ').intersection('2015-03-25T12:22:21'))`
[OUT]: ['-', 'T']
为什么第一个与第一个空格相反?我如何才能做到这一点以获得一致的订单?

无法维持订单,您必须通过循环来实现

output = []
for i in '2015-03-25 12:22:21':
    if i not in output and i in '/|.-T ']:
        output.append(i)
输出:

['-', ' ']

这是一个保留分隔符原始顺序且不输出重复分隔符的版本。当存在重复项时,输出中仅包含第一个

def date_separators(datestring, seps):
    out = []
    for s in datestring:
        if s in seps and s not in out:
            out.append(s)
    return out

# test

data = (
    '2015-03-25 12:22:21',
    '2015-03-25T12:22:23',
    '5/6/2016 12:22:25 ',
)

seps = frozenset('/|.-T ')
for s in data:
    print(s, date_separators(s, seps))
输出

2015-03-25 12:22:21 ['-', ' ']
2015-03-25T12:22:23 ['-', 'T']
5/6/2016 12:22:25  ['/', ' ']

不过,在中对集合进行
测试会更快。因此,您可以在列表编译之前执行类似于
seps=set('/.-T')
的操作。但是,不要将该
set
调用放在list comp中,因为这会对输入字符串中的每个字符重新执行。“在
中对集合进行
测试会更快”,这在技术上是不正确的。对于大型集合,它会更快,因为它具有恒定的计算复杂性。但常数并不总是意味着尽可能低的点。我想6个字符就足够让set更快了。IIRC,是set vs list,但我不记得set vs str的交叉点。