Hus*_*aad 0 python string list
我在我的代码中喜欢这个数组:
x = ['"google"','"facebook"',"youtube"]
Run Code Online (Sandbox Code Playgroud)
我希望输出将是这样的
["google","facebook","youtube"]
Run Code Online (Sandbox Code Playgroud)
怎么做?
使用str.strip和列表理解
In [1062]: x = ['"google"','"facebook"',"youtube"]
In [1063]: [i.strip('"') for i in x]
Out[1063]: ['google', 'facebook', 'youtube']
Run Code Online (Sandbox Code Playgroud)
或者,您可以使用map而不是列表理解
In [1065]: list(map(lambda i: i.strip('"'), x))
Out[1065]: ['google', 'facebook', 'youtube']
Run Code Online (Sandbox Code Playgroud)
你也可以使用 str.replace
In [1074]: [i.replace('"', '') for i in x]
Out[1074]: ['google', 'facebook', 'youtube']
Run Code Online (Sandbox Code Playgroud)
比较所有三个,列表理解str.strip是最快的
In [1066]: %timeit([i.strip('"') for i in x])
The slowest run took 12.16 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 805 ns per loop
In [1067]: %timeit(list(map(lambda i: i.strip('"'), x)))
1000000 loops, best of 3: 1.52 µs per loop
In [1075]: %timeit([i.replace('"', '') for i in x])
The slowest run took 5.48 times longer than the fastest. This could mean that an intermediate result is being cached.
1000000 loops, best of 3: 975 ns per loop
Run Code Online (Sandbox Code Playgroud)