Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python list issue

I need some hints or an example, how can i localize in a list a the list b, then replace it with list c.

a=[1,3,6,2,6,7,3,4,5,6,6,7,8]

input the b list (this is the sublist the program searches for in list a).

b=[6,7]

when found return me the indexes were the sublist has been found and replace it each time with c=[0,0], so the result will be

[1,3,6,2,0,0,3,4,5,6,0,0,8]
like image 220
Bogdan Maier Avatar asked Oct 27 '11 08:10

Bogdan Maier


People also ask

Are there bugs in Python?

There are mainly 5 types of bugs in Python: Syntax errors: When you receive a syntax error message, it indicates that you typed something wrong. Indentation errors: Python uses indentation to understand where blocks of code start and end.

How do you report a bug in Python?

Issue reports for Python itself should be submitted via the GitHub issues tracker (https://github.com/python/cpython/issues). The GitHub issues tracker offers a web form which allows pertinent information to be entered and submitted to the developers.


2 Answers

Here's a more efficient approach than my first, using list-slicing:

>>> for i in xrange(len(a) - len(b) + 1):
...     if a[i:i+len(b)] == b:
...         a[i:i+len(b)] = c
... 
>>> a
[1, 3, 6, 2, 0, 0, 3, 4, 5, 6, 0, 0, 8]

First attempt, for posterity....

If you don't need the intermediate indices, here's one approach, using string functions and taking a functional approach, not modifying your list in-place.

>>> a_as_str = ','.join(str(i) for i in a)
>>> print a_as_str
1,3,6,2,6,7,3,4,5,6,6,7,8
>>> b_as_str = ','.join(str(i) for i in b)
>>> b_as_str
'6,7'
>>> c_as_str = ','.join(str(i) for i in c)
>>> c_as_str
'0,0'
>>> replaced = a_as_str.replace(b_as_str, c_as_str)
>>> replaced
'1,3,6,2,0,0,3,4,5,6,0,0,8'
>>> [int(i) for i in replaced.split(',')]
[1, 3, 6, 2, 0, 0, 3, 4, 5, 6, 0, 0, 8]

This can be refactored as:

>>> def as_str(l):
...     return ','.join(str(i) for i in l)
... 
>>> def as_list_of_ints(s):
...     return [int(i) for i in s.split(',')]
... 
>>> as_list_of_ints(as_str(a).replace(as_str(b), as_str(c)))
[1, 3, 6, 2, 0, 0, 3, 4, 5, 6, 0, 0, 8]
like image 130
Johnsyweb Avatar answered Sep 20 '22 05:09

Johnsyweb


you can do something similar to (written in python 3.2, use xrange in python 2.x):

for i in range(0, len(a)):
    if a[i:i+len(b)] == b:
        a[i:i+len(b)] = c

this will account for lists of all sizes. This assumes list b == list c I don't know if that is what you want however, please state if it is not.

Output for lists:

a = [1,2,3,4,5,6,7,8,9,0]
b = [1,2]
c = [0,0]
Output:
[0, 0, 3, 4, 5, 6, 7, 8, 9, 0]
like image 30
Serdalis Avatar answered Sep 22 '22 05:09

Serdalis