移动列表中的元素? |蟒蛇

时间:2016-10-29 03:40:52

标签: python list

所以我想例如,如果列表中包含

之类的元素
 [A,B,C,.,D] 

我如何让'C'进入它右边的空白区域?我知道我首先要看一下角色旁边是否有一段时间。我遇到的问题是移动部分。我想移动'C'并将其移动到它的旧位置。

3 个答案:

答案 0 :(得分:3)

你的意思是,改变C和点位置?你可以有类似的东西:

In [7]: tmp.iloc[:,0]
Out[7]: 
0    1
1    2
2    3
Name: item, dtype: int64

In [8]: tmp.apply(test, axis=0)
Out[8]: 
   item  score
0     1    0.0
1     2    0.0
2     3    0.0

list_看起来像[A,B,。,C,D]。

答案 1 :(得分:1)

首先必须找到要交换的元素的位置,然后你可以像这样交换:

>>> l = ["A", "B", "C", ".", "D"]
>>> c_i = l.index("C")
>>> l[c_i], l[c_i+1] = l[c_i+1], l[c_i]
>>> l
['A', 'B', '.', 'C', 'D']

答案 2 :(得分:1)

my_list = ['A', 'B', 'C', '.', 'D']
old_index = my_list.index('.')
# Pop out the '.' and insert into the preceding index.
my_list.insert(old_index - 1, my_list.pop(old_index))
print(my_list)

> ['A', 'B', '.', 'C', 'D']
相关问题