我有一个清单:
ab = [1, 2, a, b, c]
我做了:
strab = str(ab).
所以strab
现在是一个字符串。
我想将该字符串强制转换为列表。
我该怎么做?
答案 0 :(得分:16)
最简单,最安全的方法是使用ast.literal_eval()
:
import ast
ab = [1, 2, 'a', 'b', 'c'] # a list
strab = str(ab) # the string representation of a list
strab
=> "[1, 2, 'a', 'b', 'c']"
lst = ast.literal_eval(strab) # convert string representation back to list
lst
=> [1, 2, 'a', 'b', 'c']
ab == lst # sanity check: are they equal?
=> True # of course they are!
请注意,调用eval()
也有效,但it's not safe并且您不应该使用它:
eval(strab)
=> [1, 2, 'a', 'b', 'c']
答案 1 :(得分:6)
使用ast包:
import ast
lst = ast.literal_eval(strab)
答案 2 :(得分:0)
在使用序列设置numpy数组元素的上下文中,您可以使用内置联接来绕过将其设置为字符串:
og_list_obj = str_list_obj.split("-")
然后在需要时再次使用相同的连接器拆分字符串序列(前提是它没有出现在列表的字符串中):
with data(t) as (
values
('message'),
('message s'),
('message sag'),
('message sag sag'),
('message sag sage')
)
select
t as "text",
show_trgm(t) as "text trigrams",
show_trgm('sage') as "string trigrams",
cardinality(array_intersect(show_trgm(t), show_trgm('sage'))) as "common trgms"
from data;
text | text trigrams | string trigrams | common trgms
------------------+-----------------------------------------------------------+-----------------------------+--------------
message | {" m"," me",age,ess,"ge ",mes,sag,ssa} | {" s"," sa",age,"ge ",sag} | 3
message s | {" m"," s"," me"," s ",age,ess,"ge ",mes,sag,ssa} | {" s"," sa",age,"ge ",sag} | 4
message sag | {" m"," s"," me"," sa","ag ",age,ess,"ge ",mes,sag,ssa} | {" s"," sa",age,"ge ",sag} | 5
message sag sag | {" m"," s"," me"," sa","ag ",age,ess,"ge ",mes,sag,ssa} | {" s"," sa",age,"ge ",sag} | 5
message sag sage | {" m"," s"," me"," sa","ag ",age,ess,"ge ",mes,sag,ssa} | {" s"," sa",age,"ge ",sag} | 5
(5 rows)