[英]converting a list of type [("['str']", int), ("['str']", int)] to [('str', int), ('str', int)]
i have a list of type我有一个类型列表
[("['106.52.116.101']", 1), ("['45.136.108.85']", 1)]
and want to convert it to并想将其转换为
[('106.52.116.101', 1), ('45.136.108.85', 1)]
There is more than one way to solve this, you can do this for example:有不止一种方法可以解决这个问题,您可以这样做,例如:
lst = [("['106.52.116.101']", 1), ("['45.136.108.85']", 1)]
new = [(l[0][2:-2], l[1]) for l in lst]
print(new)
Output:输出:
[('106.52.116.101', 1), ('45.136.108.85', 1)]
You can use split() of string as below:您可以使用 split() 字符串如下:
lst = [("['106.52.116.101']", 1), ("['45.136.108.85']", 1)]
print(lst)
new_lst = [(first.split('\'')[1], sec)for first, sec in lst]
print(new_lst)
output输出
[("['106.52.116.101']", 1), ("['45.136.108.85']", 1)]
[('106.52.116.101', 1), ('45.136.108.85', 1)]
you can use ast.literal_eval
:你可以使用
ast.literal_eval
:
from ast import literal_eval
l = [("['106.52.116.101']", 1), ("['45.136.108.85']", 1)]
l = [(literal_eval(f)[0], s) for f, s in l]
l
output:输出:
[('106.52.116.101', 1), ('45.136.108.85', 1)]
Mateen Ulhaq already presented a very short and good solution. Mateen Ulhaq已经提出了一个非常简短和很好的解决方案。
But if the array does not always have one item in it you can use this:但是如果数组中并不总是有一个项目,你可以使用这个:
[(eval(s)[0], n) for s, n in list]
As eval()
interpretes python code the strings have to be syntactically correct.当
eval()
解释 python 代码时,字符串必须在语法上正确。 Also pay attention if these strings come from a user in terms of security.还要注意这些字符串是否来自安全方面的用户。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.