从{a-b,b-c,c-a}改变为{(a,b),(b,c),(c,a)}?
问题描述:
v = input("enter the vertices: ")
v = [x.strip(' ') for x in v.split(',')]
e = input("enter the edges: ")
e = [x.strip(' ') for x in e.split(',')]
edges = set(e)
print(edges)
正如标题所说,我想将输出设置从{'a-b', 'c-a', 'b-c'}
更改为{('a','b'),('b','c'),('c','a')}
,因此更容易将数据引用为边缘。我将如何做到这一点?从{a-b,b-c,c-a}改变为{(a,b),(b,c),(c,a)}?
答
用于转换{'a-b', 'c-a', 'b-c'}
到{('a','b'),('b','c'),('c','a')}
,您可以使用发电机表达每个字符串项在您所设定的分割基于-
为:
>>> input_set = {'a-b','b-c','c-a'}
# v `str.split()` returns list. And list are non-hashable.
# v type-cast it to tuple in order to use it with `set`.
>>> output_Set = set(tuple(s.split('-')) for s in input_set)
>>> output_Set
{('c', 'a'), ('b', 'c'), ('a', 'b')}
但是,您不需要创建一组的字符串。如果你想在第一次迭代中创建所需的集合,你可以这样做:
v = set(x.strip().split('-') for x in v.split(','))
答
你可以简单的分析上'-'
使用一套理解和分裂的边缘:
e = input("enter the edges: ")
e = {tuple(x.strip().split('-')) for x in e.split(',')}
只需使用tuple(x.strip()。split(' - '))'边缘。 – dnswlt
请不要破坏你的帖子。一旦你发布了一个问题,它就一般属于Stack Overflow社区(在CC-by-SA许可下)。如果您想取消关联该帐户与您的帐户的关联,请参阅[解除请求的正确途径是什么?](http://meta.*.com/questions/323395/what-is-the-proper-rout的e-FOR-A - 解离 - 请求) – tripleee