有些人正在回答错误的问题,看来。你说你想做:
>>> first_item, last_item = some_list[0,-1]
>>> print first_item
'1'
>>> print last_item
'F'
也就是说,你想要提取第一个和最后一个元素到单独的变量。
在这种情况下,Matthew Adams,pemistahl和katrielalex的答案是有效的。这仅仅是一个复合赋值:
first_item, last_item = some_list[0], some_list[-1]
但后来你说出一个复杂:“我分裂它在同一直线上,并且将不得不花费时间分裂两次:”
x, y = a.split("-")[0], a.split("-")[-1]
因此,为了避免两次split()调用,您只能在分割一次的列表上进行操作。
在这种情况下,尝试在一行中做太多操作对清晰和简单而言是不利的。使用一个变量来保存分割结果:“如何获得新的列表,包括列表的第一个和最后一个元素的”
lst = a.split("-")
first_item, last_item = lst[0], lst[-1]
其他答复回答的问题根据仔细阅读你的问题,他们可能受到你的标题的启发,该标题提到了切片,你实际上不希望切片。
AFAIK有3种方式来获得与第0和列表的最后一个元素的新列表:
>>> s = 'Python ver. 3.4'
>>> a = s.split()
>>> a
['Python', 'ver.', '3.4']
>>> [ a[0], a[-1] ] # mentioned above
['Python', '3.4']
>>> a[::len(a)-1] # also mentioned above
['Python', '3.4']
>>> [ a[e] for e in (0,-1) ] # list comprehension, nobody mentioned?
['Python', '3.4']
# Or, if you insist on doing it in one line:
>>> [ s.split()[e] for e in (0,-1) ]
['Python', '3.4']
列表理解方法的优点是,在元组中的一组指标,可任意并以编程方式生成。
哈哈3个答案中,相同,以2秒的间隔,以及一个是你。经典。 – Aesthete
'first,last = some_list [0],some_list [-1]'有什么不好? –
@MatthewAdams因为我在同一行中分割它,所以需要花费两次时间来分割它:'x,y = a.split(“ - ”)[0],a.split(“ - ”)[ -1]'。 – chown