从文本文件行读取后,我有一个这样的字符串:
poLCA::poLCA()
我想将其转换为元组。我在做的是:
#Latent class models with one (loglinear independence) to three classes
f=cbind("I_like_to_drink","I_drink_hard_liquor","I_have_drank_in_the_morning","I_have_drank_in_the_work","I_drink_to_get_drunk","I_like_the_taste_of_the_alcohol","I_drink_help_me_sleep","Drinking_interferes_with_my_relationships","I_frequently_visit_bars")~1
nes1 = poLCA(f,lca1,nclass=1) # log-likelihood:
nes2 = poLCA(f,lca1,nclass=2) # log-likelihood:
nes3 = poLCA(f,lca1,nclass=3) # log-likelihood:
nes4 = poLCA(f,lca1,nclass=4) # log-likelihood:
预计我需要将每个值除以To = "'abc@hcl.com','xyz@hcl.com','accc@infy.com','satya@lab.com','ach@lab.com'"
并将其存储到字符串或元组转换后的元组中:
To = (To,)
type(To) #o/p tuple
len(To) #1
To
("'abc@hcl.com','xyz@hcl.com','accc@infy.com', 'sat@lab.com','ach@lab.com'",) # output tuple
答案 0 :(得分:7)
使用Abstract Syntax Trees,如下所示 -
>>>import ast
>>>To=ast.literal_eval(To)
>>>print To
>>>('abc@hcl.com', 'xyz@hcl.com', 'accc@infy.com', 'satya@lab.com', 'ach@lab.com')
>>>len(To)
>>>5
答案 1 :(得分:2)
或者如果你不想使用ast,你可以简单地运行:
tuple(word[1:-1] for word in To.split(","))
答案 2 :(得分:2)
备注:强>
String
List
转换为,
List
转换为Tuple
<强>代码:强>
To = "'abc@hcl.com','xyz@hcl.com','accc@infy.com','satya@lab.com','ach@lab.com'"
print tuple(To.split(","))
<强>输出:强>
("'abc@hcl.com'", "'xyz@hcl.com'", "'accc@infy.com'", "'satya@lab.com'", "'ach@lab.com'")
如果您要删除'
引号
<强>代码1:强>
print tuple(elem.strip("'") for elem in To.split(","))
<强>输出1:强>
('abc@hcl.com', 'xyz@hcl.com', 'accc@infy.com', 'satya@lab.com', 'ach@lab.com')