开发者

List values from one to another list

I am almost new to python and I am stuck with a seemingly simple problem. I got two lists

L1 = [a,b,c]
L2 = [1,2,3]

now I want to replace the values from L2 to L1 beco开发者_高级运维ming L1 = [1,2,3]

Now this is where the fun comes in

the length of L2 is always how many unique items there can be in L1 eg.

L2 = [1,2,3,4,5]
than
L1 = [a,b,c,d,e]
or
L2 = [1,2]
than
L1 = [a,b]

but thats not all... L1 can be different in length and unordered after the length of L2..:

eg:

L2 = [1,2]
than L1 might be
L1 = [a,b,a,a,a,b] #(first two items are always different)
or
L2 = [1,2,3,4,5]
than L1 might be
L1 = [a,b,c,d,e,a,a,e,e,b,b] #(first 5 items are different) 

I hope I explained it good enough. If there are any question feel free to ask!

I hope someone can help me out or give me a hint where or what to search for. I am trying to solve this since days.

thx in advance

jaden

_edit__

L1 and L2 are created early in my script. Now I somehow want to connect the items in both lists.

L1[0] = L2[0]
L1[1] = L2[1]

and so on. for the lenght of L2, but it has to happen for every item in L1 since L1 is always longer than L2. Thats the problem.

Hope this helps,

jaden


You can replace slices of the list.

>>> L1 = ['a','b','c','d','e','a','a','e','e','b','b']
>>> L2 = [1,2,3,4,5]
>>> length = len(L2)
>>> L1[:length] = L2[:length]
>>> print(L1)
[1, 2, 3, 4, 5, 'a', 'a', 'e', 'e', 'b', 'b']

Just in case I misinterpreted what you wanted and want to replace every instance of 'a' with 1, 'b' with 2, etc., this works:

>>> L1 = ['a','b','c','d','e','a','a','e','e','b','b']
>>> L2 = [1,2,3,4,5]
>>> mapping = dict(zip(L1, L2))
>>> for i, k in enumerate(L1[:]):
        L1[i] = mapping[k]
>>> print(L1)
[1, 2, 3, 4, 5, 1, 1, 5, 5, 2, 2]


You can create a dictionary containing the mappings of the values from l1 to l2, { 'a':1, 'b':2,....}, then iterate over l1 and replace the values.

d = dict ((l1[idx],y) for idx, y in enumerate(l2))
l1 = [d[x] for x in l1]

EDIT: For a better understanding of your question it would be helpful to post the expected outputs for the given examples.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜