Create a tuple from a string and a list of strings

夙愿已清 提交于 2019-11-30 00:47:23

问题


I need to combine a string along with a list of strings into a tuple so I can use it as a dictionary key. This is going to be in an inner loop so speed is important.

The list will be small (usually 1, but occasionally 2 or 3 items).

What is the fastest way to do this?

Before:

my_string == "foo"
my_list == ["bar", "baz", "qux", "etc"]

After:

my_tuple == ("foo", "bar", "baz", "qux", "etc")

(Note: my_list must not be altered itself).


回答1:


I can't speak for performance, but this is definitely the simplest I can think of:

my_tuple = tuple([my_string] + my_list)



回答2:


The straightforward way is simply my_tuple = tuple( my_list + [my_string] ). I would certainly start with that and see if the performance is acceptable before trying to figure out any crazy ways of subverting the normal system for speed.




回答3:


i think this way is better:

my_list = my_list.insert(0,my_string)
my_tuple = tuple(my_list)


来源:https://stackoverflow.com/questions/5453979/create-a-tuple-from-a-string-and-a-list-of-strings

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!