How to increment through a list and replace certain values with their countsHow do I check if a list is empty?How do I sort a list of dictionaries by a value of the dictionary?Converting string into datetimeHow do I sort a dictionary by value?How to make a flat list out of list of listsHow do I concatenate two lists in Python?How can I count the occurrences of a list item?How to clone or copy a list?How do I list all files of a directory?How to read a file line-by-line into a list?

Did any of the founding fathers anticipate Lysander Spooner's criticism of the constitution?

Are randomly-generated passwords starting with "a" less secure?

How did the hit man miss?

Print the last, middle and first character of your code

Is "take care'n of" correct?

definition of "percentile"

Why didn't Thanos kill all the Dwarves on Nidavellir?

How to know whether a Tamron lens is compatible with Canon EOS 60D?

Is purchasing foreign currency before going abroad a losing proposition?

How can one write good dialogue in a story without sounding wooden?

Single word for "refusing to move to next activity unless present one is completed."

What is this welding tool I found in my attic?

Graduate student with abysmal English writing skills, how to help

How to tell someone I'd like to become friends without causing them to think I'm romantically interested in them?

How would my creatures handle groups without a strong concept of numbers?

Why does my script create an extra character?

Managing and organizing the massively increased number of classes after switching to SOLID?

What's the minimum number of sensors for a hobby GPS waypoint-following UAV?

The monorail explodes before I can get on it

Is there any word for "disobedience to God"?

How can I deal with a player trying to insert real-world mythology into my homebrew setting?

A pyramid from a square

As the Dungeon Master, how do I handle a player that insists on a specific class when I already know that choice will cause issues?

What does "it kind of works out" mean?



How to increment through a list and replace certain values with their counts


How do I check if a list is empty?How do I sort a list of dictionaries by a value of the dictionary?Converting string into datetimeHow do I sort a dictionary by value?How to make a flat list out of list of listsHow do I concatenate two lists in Python?How can I count the occurrences of a list item?How to clone or copy a list?How do I list all files of a directory?How to read a file line-by-line into a list?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








1















I'm trying to increment through a list and replace multiple occurrences (in sequence) of a given value with the amount of times they occurred (as a rough range, with occurrences of 1-3 being small, 4-6 being medium, and more than 6 being a large amount of times).



I am trying to find an elegant solution to this problem and hoping for any guidance. I looked through itertools but couldn't find something suitable for this (I think).



Any help would be greatly appreciated. Thank you



So for instance:



testList = [1, 2, 2, 1, 1, 2, 1, 4, 1, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]



will become



[1, "2 small amount of times", 1, 1, "2 small amount of times", 1, 4, 1, "2 medium amount of times", 1, "2 large amount of times"]



testList = [1, 2, 2, 1, 1, 2, 1, 4, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]

listLocation = -1

newlist = []

for i in testList:

listLocation += 1

if i == 2:

if testList[listLocation+1] == 2:

testList[listLocation] = "2 multiple"

newlist.append(testList[listLocation])

testList.pop(listLocation+1)

else:
newlist.append(i)

newlist


This is as far as I've gotten, right now this just detects when 2 occurs multiple times in sequence and replaces that sequence with a string, but I can't work out how to move from this to an actual counter that bins it by ranges and a more elegant style of code (I'm sure there is a way to avoid having the listLocation variable to keep track of list index). Also I can't work out how to detect the end of the list because right now this will crash if it hits a 2 as the last value in the list.



Any help would be greatly appreciated, thank you










share|improve this question






















  • You mean "iterate through a list". "Increment" would give you [2,3,3,2,...] Anyway what you're looking for here is called run-length encoding.

    – smci
    Mar 26 at 4:57


















1















I'm trying to increment through a list and replace multiple occurrences (in sequence) of a given value with the amount of times they occurred (as a rough range, with occurrences of 1-3 being small, 4-6 being medium, and more than 6 being a large amount of times).



I am trying to find an elegant solution to this problem and hoping for any guidance. I looked through itertools but couldn't find something suitable for this (I think).



Any help would be greatly appreciated. Thank you



So for instance:



testList = [1, 2, 2, 1, 1, 2, 1, 4, 1, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]



will become



[1, "2 small amount of times", 1, 1, "2 small amount of times", 1, 4, 1, "2 medium amount of times", 1, "2 large amount of times"]



testList = [1, 2, 2, 1, 1, 2, 1, 4, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]

listLocation = -1

newlist = []

for i in testList:

listLocation += 1

if i == 2:

if testList[listLocation+1] == 2:

testList[listLocation] = "2 multiple"

newlist.append(testList[listLocation])

testList.pop(listLocation+1)

else:
newlist.append(i)

newlist


This is as far as I've gotten, right now this just detects when 2 occurs multiple times in sequence and replaces that sequence with a string, but I can't work out how to move from this to an actual counter that bins it by ranges and a more elegant style of code (I'm sure there is a way to avoid having the listLocation variable to keep track of list index). Also I can't work out how to detect the end of the list because right now this will crash if it hits a 2 as the last value in the list.



Any help would be greatly appreciated, thank you










share|improve this question






















  • You mean "iterate through a list". "Increment" would give you [2,3,3,2,...] Anyway what you're looking for here is called run-length encoding.

    – smci
    Mar 26 at 4:57














1












1








1








I'm trying to increment through a list and replace multiple occurrences (in sequence) of a given value with the amount of times they occurred (as a rough range, with occurrences of 1-3 being small, 4-6 being medium, and more than 6 being a large amount of times).



I am trying to find an elegant solution to this problem and hoping for any guidance. I looked through itertools but couldn't find something suitable for this (I think).



Any help would be greatly appreciated. Thank you



So for instance:



testList = [1, 2, 2, 1, 1, 2, 1, 4, 1, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]



will become



[1, "2 small amount of times", 1, 1, "2 small amount of times", 1, 4, 1, "2 medium amount of times", 1, "2 large amount of times"]



testList = [1, 2, 2, 1, 1, 2, 1, 4, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]

listLocation = -1

newlist = []

for i in testList:

listLocation += 1

if i == 2:

if testList[listLocation+1] == 2:

testList[listLocation] = "2 multiple"

newlist.append(testList[listLocation])

testList.pop(listLocation+1)

else:
newlist.append(i)

newlist


This is as far as I've gotten, right now this just detects when 2 occurs multiple times in sequence and replaces that sequence with a string, but I can't work out how to move from this to an actual counter that bins it by ranges and a more elegant style of code (I'm sure there is a way to avoid having the listLocation variable to keep track of list index). Also I can't work out how to detect the end of the list because right now this will crash if it hits a 2 as the last value in the list.



Any help would be greatly appreciated, thank you










share|improve this question














I'm trying to increment through a list and replace multiple occurrences (in sequence) of a given value with the amount of times they occurred (as a rough range, with occurrences of 1-3 being small, 4-6 being medium, and more than 6 being a large amount of times).



I am trying to find an elegant solution to this problem and hoping for any guidance. I looked through itertools but couldn't find something suitable for this (I think).



Any help would be greatly appreciated. Thank you



So for instance:



testList = [1, 2, 2, 1, 1, 2, 1, 4, 1, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]



will become



[1, "2 small amount of times", 1, 1, "2 small amount of times", 1, 4, 1, "2 medium amount of times", 1, "2 large amount of times"]



testList = [1, 2, 2, 1, 1, 2, 1, 4, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]

listLocation = -1

newlist = []

for i in testList:

listLocation += 1

if i == 2:

if testList[listLocation+1] == 2:

testList[listLocation] = "2 multiple"

newlist.append(testList[listLocation])

testList.pop(listLocation+1)

else:
newlist.append(i)

newlist


This is as far as I've gotten, right now this just detects when 2 occurs multiple times in sequence and replaces that sequence with a string, but I can't work out how to move from this to an actual counter that bins it by ranges and a more elegant style of code (I'm sure there is a way to avoid having the listLocation variable to keep track of list index). Also I can't work out how to detect the end of the list because right now this will crash if it hits a 2 as the last value in the list.



Any help would be greatly appreciated, thank you







python






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Mar 26 at 2:46









rortestrortest

102 bronze badges




102 bronze badges












  • You mean "iterate through a list". "Increment" would give you [2,3,3,2,...] Anyway what you're looking for here is called run-length encoding.

    – smci
    Mar 26 at 4:57


















  • You mean "iterate through a list". "Increment" would give you [2,3,3,2,...] Anyway what you're looking for here is called run-length encoding.

    – smci
    Mar 26 at 4:57

















You mean "iterate through a list". "Increment" would give you [2,3,3,2,...] Anyway what you're looking for here is called run-length encoding.

– smci
Mar 26 at 4:57






You mean "iterate through a list". "Increment" would give you [2,3,3,2,...] Anyway what you're looking for here is called run-length encoding.

– smci
Mar 26 at 4:57













3 Answers
3






active

oldest

votes


















0














Here is my solution. First, let's define a function which returns a message to be inserted into the list:



def message(value, count):
msg = 'value amount amount of times'

if 1 <= count <= 3:
msg = msg.format(value=value, amount='small')
elif 4 <= count <= 6:
msg = msg.format(value=value, amount='medium')
else:
msg = msg.format(value=value, amount='large')

return msg


Second, we define a function which takes a list of values and a value to be counted as its arguments:



def counter(values, value):
count = 0
results = []

for i, v in enumerate(values):

if v != value:

if count:
results.append(message(value, count))
count = 0

results.append(v)
continue

count = count + 1

if i < len(values) - 1:
continue

results.append(message(value, count))

return results


Here is the result:



>>> values = [1, 2, 2, 1, 1, 2, 1, 4, 1, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]
>>> counter(values, value=2)
[1,
'2 small amount of times',
1,
1,
'2 small amount of times',
1,
4,
1,
'2 medium amount of times',
1,
'2 large amount of times',
1]





share|improve this answer























  • This is a fantastic and elegant solution thank you constt.

    – rortest
    Mar 26 at 5:11


















1














Here's what I think is a simple way to do it.



a = [1, 2, 2, 1, 1, 2, 1, 4, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]
b = []
i=0
while i<len(a) and i < len(a):
if a[i]==2:
n=i
while a[i]==2:
i+=1

if (i-n)<4:
b.append("2 small amount of times")
elif (i-n)<6 and (i-n)>4:
b.append("2 medium amount of times")
else:
b.append("2 large amount of times")

else:
b.append(a[i])
i+=1
print(b)


Outputs:



[1, '2 small amount of times', 1, 1, '2 small amount of times', 1, 4, 1, '2 large amount of times', 1, '2 large amount of times', 1]


Let me know if you have any queries.






share|improve this answer

























  • Super clever, thank you Haran, implementing.

    – rortest
    Mar 26 at 4:38











  • No problem! If this helped, kindly accept the answer!

    – Haran Rajkumar
    Mar 26 at 4:49











  • Quick query = this only works on lists that don't end in 2. If you try running a = [1, 2, 2] it won't work and has an index error.

    – rortest
    Mar 26 at 5:02











  • Also if you run, a = [1, 2, 2, 2, 5], it should come out as a medium amount of times, but it comes out as a large amount of times for some reason, any help on this would be appreciated thanks Haran

    – rortest
    Mar 26 at 5:06












  • Apologies for the errors. I've fixed them now.

    – Haran Rajkumar
    Mar 26 at 5:18


















0














If you want to group all the numbers in the list, you can first create a list of lists, and then regroup them.



First to create a list of lists with the same number:



def group_list(input_list):
l,s = [], 0
for i in range(len(input_list)):
try:
if input_list[i] != input_list[i+1]:
l.append(input_list[s:i+1])
s=i+1
except IndexError:
if input_list[i] == input_list[i-1]:
l.append(input_list[s:i+1])
else:
l.append([input_list[i]])
return l


Then apply the amount message:



def message(num):
if num > 6:
return 'large'
elif num >4:
return 'medium'
else:
return 'small'


With both functions ready, do a list comprehension.



another_list = [i[0] if len(i)<2 else f"i[0] message(len(i)) amount of times" for i in group_list(testList)]

print (another_list)


Result:



[1, '2 small amount of times', '1 small amount of times', 2, 1, '4 small amount of times', 1, '2 medium amount of times', 1, '2 large amount of times', 1]





share|improve this answer

























    Your Answer






    StackExchange.ifUsing("editor", function ()
    StackExchange.using("externalEditor", function ()
    StackExchange.using("snippets", function ()
    StackExchange.snippets.init();
    );
    );
    , "code-snippets");

    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "1"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: true,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: 10,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55349136%2fhow-to-increment-through-a-list-and-replace-certain-values-with-their-counts%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    3 Answers
    3






    active

    oldest

    votes








    3 Answers
    3






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    0














    Here is my solution. First, let's define a function which returns a message to be inserted into the list:



    def message(value, count):
    msg = 'value amount amount of times'

    if 1 <= count <= 3:
    msg = msg.format(value=value, amount='small')
    elif 4 <= count <= 6:
    msg = msg.format(value=value, amount='medium')
    else:
    msg = msg.format(value=value, amount='large')

    return msg


    Second, we define a function which takes a list of values and a value to be counted as its arguments:



    def counter(values, value):
    count = 0
    results = []

    for i, v in enumerate(values):

    if v != value:

    if count:
    results.append(message(value, count))
    count = 0

    results.append(v)
    continue

    count = count + 1

    if i < len(values) - 1:
    continue

    results.append(message(value, count))

    return results


    Here is the result:



    >>> values = [1, 2, 2, 1, 1, 2, 1, 4, 1, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]
    >>> counter(values, value=2)
    [1,
    '2 small amount of times',
    1,
    1,
    '2 small amount of times',
    1,
    4,
    1,
    '2 medium amount of times',
    1,
    '2 large amount of times',
    1]





    share|improve this answer























    • This is a fantastic and elegant solution thank you constt.

      – rortest
      Mar 26 at 5:11















    0














    Here is my solution. First, let's define a function which returns a message to be inserted into the list:



    def message(value, count):
    msg = 'value amount amount of times'

    if 1 <= count <= 3:
    msg = msg.format(value=value, amount='small')
    elif 4 <= count <= 6:
    msg = msg.format(value=value, amount='medium')
    else:
    msg = msg.format(value=value, amount='large')

    return msg


    Second, we define a function which takes a list of values and a value to be counted as its arguments:



    def counter(values, value):
    count = 0
    results = []

    for i, v in enumerate(values):

    if v != value:

    if count:
    results.append(message(value, count))
    count = 0

    results.append(v)
    continue

    count = count + 1

    if i < len(values) - 1:
    continue

    results.append(message(value, count))

    return results


    Here is the result:



    >>> values = [1, 2, 2, 1, 1, 2, 1, 4, 1, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]
    >>> counter(values, value=2)
    [1,
    '2 small amount of times',
    1,
    1,
    '2 small amount of times',
    1,
    4,
    1,
    '2 medium amount of times',
    1,
    '2 large amount of times',
    1]





    share|improve this answer























    • This is a fantastic and elegant solution thank you constt.

      – rortest
      Mar 26 at 5:11













    0












    0








    0







    Here is my solution. First, let's define a function which returns a message to be inserted into the list:



    def message(value, count):
    msg = 'value amount amount of times'

    if 1 <= count <= 3:
    msg = msg.format(value=value, amount='small')
    elif 4 <= count <= 6:
    msg = msg.format(value=value, amount='medium')
    else:
    msg = msg.format(value=value, amount='large')

    return msg


    Second, we define a function which takes a list of values and a value to be counted as its arguments:



    def counter(values, value):
    count = 0
    results = []

    for i, v in enumerate(values):

    if v != value:

    if count:
    results.append(message(value, count))
    count = 0

    results.append(v)
    continue

    count = count + 1

    if i < len(values) - 1:
    continue

    results.append(message(value, count))

    return results


    Here is the result:



    >>> values = [1, 2, 2, 1, 1, 2, 1, 4, 1, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]
    >>> counter(values, value=2)
    [1,
    '2 small amount of times',
    1,
    1,
    '2 small amount of times',
    1,
    4,
    1,
    '2 medium amount of times',
    1,
    '2 large amount of times',
    1]





    share|improve this answer













    Here is my solution. First, let's define a function which returns a message to be inserted into the list:



    def message(value, count):
    msg = 'value amount amount of times'

    if 1 <= count <= 3:
    msg = msg.format(value=value, amount='small')
    elif 4 <= count <= 6:
    msg = msg.format(value=value, amount='medium')
    else:
    msg = msg.format(value=value, amount='large')

    return msg


    Second, we define a function which takes a list of values and a value to be counted as its arguments:



    def counter(values, value):
    count = 0
    results = []

    for i, v in enumerate(values):

    if v != value:

    if count:
    results.append(message(value, count))
    count = 0

    results.append(v)
    continue

    count = count + 1

    if i < len(values) - 1:
    continue

    results.append(message(value, count))

    return results


    Here is the result:



    >>> values = [1, 2, 2, 1, 1, 2, 1, 4, 1, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]
    >>> counter(values, value=2)
    [1,
    '2 small amount of times',
    1,
    1,
    '2 small amount of times',
    1,
    4,
    1,
    '2 medium amount of times',
    1,
    '2 large amount of times',
    1]






    share|improve this answer












    share|improve this answer



    share|improve this answer










    answered Mar 26 at 4:37









    consttconstt

    8041 gold badge10 silver badges12 bronze badges




    8041 gold badge10 silver badges12 bronze badges












    • This is a fantastic and elegant solution thank you constt.

      – rortest
      Mar 26 at 5:11

















    • This is a fantastic and elegant solution thank you constt.

      – rortest
      Mar 26 at 5:11
















    This is a fantastic and elegant solution thank you constt.

    – rortest
    Mar 26 at 5:11





    This is a fantastic and elegant solution thank you constt.

    – rortest
    Mar 26 at 5:11













    1














    Here's what I think is a simple way to do it.



    a = [1, 2, 2, 1, 1, 2, 1, 4, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]
    b = []
    i=0
    while i<len(a) and i < len(a):
    if a[i]==2:
    n=i
    while a[i]==2:
    i+=1

    if (i-n)<4:
    b.append("2 small amount of times")
    elif (i-n)<6 and (i-n)>4:
    b.append("2 medium amount of times")
    else:
    b.append("2 large amount of times")

    else:
    b.append(a[i])
    i+=1
    print(b)


    Outputs:



    [1, '2 small amount of times', 1, 1, '2 small amount of times', 1, 4, 1, '2 large amount of times', 1, '2 large amount of times', 1]


    Let me know if you have any queries.






    share|improve this answer

























    • Super clever, thank you Haran, implementing.

      – rortest
      Mar 26 at 4:38











    • No problem! If this helped, kindly accept the answer!

      – Haran Rajkumar
      Mar 26 at 4:49











    • Quick query = this only works on lists that don't end in 2. If you try running a = [1, 2, 2] it won't work and has an index error.

      – rortest
      Mar 26 at 5:02











    • Also if you run, a = [1, 2, 2, 2, 5], it should come out as a medium amount of times, but it comes out as a large amount of times for some reason, any help on this would be appreciated thanks Haran

      – rortest
      Mar 26 at 5:06












    • Apologies for the errors. I've fixed them now.

      – Haran Rajkumar
      Mar 26 at 5:18















    1














    Here's what I think is a simple way to do it.



    a = [1, 2, 2, 1, 1, 2, 1, 4, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]
    b = []
    i=0
    while i<len(a) and i < len(a):
    if a[i]==2:
    n=i
    while a[i]==2:
    i+=1

    if (i-n)<4:
    b.append("2 small amount of times")
    elif (i-n)<6 and (i-n)>4:
    b.append("2 medium amount of times")
    else:
    b.append("2 large amount of times")

    else:
    b.append(a[i])
    i+=1
    print(b)


    Outputs:



    [1, '2 small amount of times', 1, 1, '2 small amount of times', 1, 4, 1, '2 large amount of times', 1, '2 large amount of times', 1]


    Let me know if you have any queries.






    share|improve this answer

























    • Super clever, thank you Haran, implementing.

      – rortest
      Mar 26 at 4:38











    • No problem! If this helped, kindly accept the answer!

      – Haran Rajkumar
      Mar 26 at 4:49











    • Quick query = this only works on lists that don't end in 2. If you try running a = [1, 2, 2] it won't work and has an index error.

      – rortest
      Mar 26 at 5:02











    • Also if you run, a = [1, 2, 2, 2, 5], it should come out as a medium amount of times, but it comes out as a large amount of times for some reason, any help on this would be appreciated thanks Haran

      – rortest
      Mar 26 at 5:06












    • Apologies for the errors. I've fixed them now.

      – Haran Rajkumar
      Mar 26 at 5:18













    1












    1








    1







    Here's what I think is a simple way to do it.



    a = [1, 2, 2, 1, 1, 2, 1, 4, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]
    b = []
    i=0
    while i<len(a) and i < len(a):
    if a[i]==2:
    n=i
    while a[i]==2:
    i+=1

    if (i-n)<4:
    b.append("2 small amount of times")
    elif (i-n)<6 and (i-n)>4:
    b.append("2 medium amount of times")
    else:
    b.append("2 large amount of times")

    else:
    b.append(a[i])
    i+=1
    print(b)


    Outputs:



    [1, '2 small amount of times', 1, 1, '2 small amount of times', 1, 4, 1, '2 large amount of times', 1, '2 large amount of times', 1]


    Let me know if you have any queries.






    share|improve this answer















    Here's what I think is a simple way to do it.



    a = [1, 2, 2, 1, 1, 2, 1, 4, 1, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 1]
    b = []
    i=0
    while i<len(a) and i < len(a):
    if a[i]==2:
    n=i
    while a[i]==2:
    i+=1

    if (i-n)<4:
    b.append("2 small amount of times")
    elif (i-n)<6 and (i-n)>4:
    b.append("2 medium amount of times")
    else:
    b.append("2 large amount of times")

    else:
    b.append(a[i])
    i+=1
    print(b)


    Outputs:



    [1, '2 small amount of times', 1, 1, '2 small amount of times', 1, 4, 1, '2 large amount of times', 1, '2 large amount of times', 1]


    Let me know if you have any queries.







    share|improve this answer














    share|improve this answer



    share|improve this answer








    edited Mar 26 at 5:17

























    answered Mar 26 at 3:30









    Haran RajkumarHaran Rajkumar

    6177 silver badges18 bronze badges




    6177 silver badges18 bronze badges












    • Super clever, thank you Haran, implementing.

      – rortest
      Mar 26 at 4:38











    • No problem! If this helped, kindly accept the answer!

      – Haran Rajkumar
      Mar 26 at 4:49











    • Quick query = this only works on lists that don't end in 2. If you try running a = [1, 2, 2] it won't work and has an index error.

      – rortest
      Mar 26 at 5:02











    • Also if you run, a = [1, 2, 2, 2, 5], it should come out as a medium amount of times, but it comes out as a large amount of times for some reason, any help on this would be appreciated thanks Haran

      – rortest
      Mar 26 at 5:06












    • Apologies for the errors. I've fixed them now.

      – Haran Rajkumar
      Mar 26 at 5:18

















    • Super clever, thank you Haran, implementing.

      – rortest
      Mar 26 at 4:38











    • No problem! If this helped, kindly accept the answer!

      – Haran Rajkumar
      Mar 26 at 4:49











    • Quick query = this only works on lists that don't end in 2. If you try running a = [1, 2, 2] it won't work and has an index error.

      – rortest
      Mar 26 at 5:02











    • Also if you run, a = [1, 2, 2, 2, 5], it should come out as a medium amount of times, but it comes out as a large amount of times for some reason, any help on this would be appreciated thanks Haran

      – rortest
      Mar 26 at 5:06












    • Apologies for the errors. I've fixed them now.

      – Haran Rajkumar
      Mar 26 at 5:18
















    Super clever, thank you Haran, implementing.

    – rortest
    Mar 26 at 4:38





    Super clever, thank you Haran, implementing.

    – rortest
    Mar 26 at 4:38













    No problem! If this helped, kindly accept the answer!

    – Haran Rajkumar
    Mar 26 at 4:49





    No problem! If this helped, kindly accept the answer!

    – Haran Rajkumar
    Mar 26 at 4:49













    Quick query = this only works on lists that don't end in 2. If you try running a = [1, 2, 2] it won't work and has an index error.

    – rortest
    Mar 26 at 5:02





    Quick query = this only works on lists that don't end in 2. If you try running a = [1, 2, 2] it won't work and has an index error.

    – rortest
    Mar 26 at 5:02













    Also if you run, a = [1, 2, 2, 2, 5], it should come out as a medium amount of times, but it comes out as a large amount of times for some reason, any help on this would be appreciated thanks Haran

    – rortest
    Mar 26 at 5:06






    Also if you run, a = [1, 2, 2, 2, 5], it should come out as a medium amount of times, but it comes out as a large amount of times for some reason, any help on this would be appreciated thanks Haran

    – rortest
    Mar 26 at 5:06














    Apologies for the errors. I've fixed them now.

    – Haran Rajkumar
    Mar 26 at 5:18





    Apologies for the errors. I've fixed them now.

    – Haran Rajkumar
    Mar 26 at 5:18











    0














    If you want to group all the numbers in the list, you can first create a list of lists, and then regroup them.



    First to create a list of lists with the same number:



    def group_list(input_list):
    l,s = [], 0
    for i in range(len(input_list)):
    try:
    if input_list[i] != input_list[i+1]:
    l.append(input_list[s:i+1])
    s=i+1
    except IndexError:
    if input_list[i] == input_list[i-1]:
    l.append(input_list[s:i+1])
    else:
    l.append([input_list[i]])
    return l


    Then apply the amount message:



    def message(num):
    if num > 6:
    return 'large'
    elif num >4:
    return 'medium'
    else:
    return 'small'


    With both functions ready, do a list comprehension.



    another_list = [i[0] if len(i)<2 else f"i[0] message(len(i)) amount of times" for i in group_list(testList)]

    print (another_list)


    Result:



    [1, '2 small amount of times', '1 small amount of times', 2, 1, '4 small amount of times', 1, '2 medium amount of times', 1, '2 large amount of times', 1]





    share|improve this answer



























      0














      If you want to group all the numbers in the list, you can first create a list of lists, and then regroup them.



      First to create a list of lists with the same number:



      def group_list(input_list):
      l,s = [], 0
      for i in range(len(input_list)):
      try:
      if input_list[i] != input_list[i+1]:
      l.append(input_list[s:i+1])
      s=i+1
      except IndexError:
      if input_list[i] == input_list[i-1]:
      l.append(input_list[s:i+1])
      else:
      l.append([input_list[i]])
      return l


      Then apply the amount message:



      def message(num):
      if num > 6:
      return 'large'
      elif num >4:
      return 'medium'
      else:
      return 'small'


      With both functions ready, do a list comprehension.



      another_list = [i[0] if len(i)<2 else f"i[0] message(len(i)) amount of times" for i in group_list(testList)]

      print (another_list)


      Result:



      [1, '2 small amount of times', '1 small amount of times', 2, 1, '4 small amount of times', 1, '2 medium amount of times', 1, '2 large amount of times', 1]





      share|improve this answer

























        0












        0








        0







        If you want to group all the numbers in the list, you can first create a list of lists, and then regroup them.



        First to create a list of lists with the same number:



        def group_list(input_list):
        l,s = [], 0
        for i in range(len(input_list)):
        try:
        if input_list[i] != input_list[i+1]:
        l.append(input_list[s:i+1])
        s=i+1
        except IndexError:
        if input_list[i] == input_list[i-1]:
        l.append(input_list[s:i+1])
        else:
        l.append([input_list[i]])
        return l


        Then apply the amount message:



        def message(num):
        if num > 6:
        return 'large'
        elif num >4:
        return 'medium'
        else:
        return 'small'


        With both functions ready, do a list comprehension.



        another_list = [i[0] if len(i)<2 else f"i[0] message(len(i)) amount of times" for i in group_list(testList)]

        print (another_list)


        Result:



        [1, '2 small amount of times', '1 small amount of times', 2, 1, '4 small amount of times', 1, '2 medium amount of times', 1, '2 large amount of times', 1]





        share|improve this answer













        If you want to group all the numbers in the list, you can first create a list of lists, and then regroup them.



        First to create a list of lists with the same number:



        def group_list(input_list):
        l,s = [], 0
        for i in range(len(input_list)):
        try:
        if input_list[i] != input_list[i+1]:
        l.append(input_list[s:i+1])
        s=i+1
        except IndexError:
        if input_list[i] == input_list[i-1]:
        l.append(input_list[s:i+1])
        else:
        l.append([input_list[i]])
        return l


        Then apply the amount message:



        def message(num):
        if num > 6:
        return 'large'
        elif num >4:
        return 'medium'
        else:
        return 'small'


        With both functions ready, do a list comprehension.



        another_list = [i[0] if len(i)<2 else f"i[0] message(len(i)) amount of times" for i in group_list(testList)]

        print (another_list)


        Result:



        [1, '2 small amount of times', '1 small amount of times', 2, 1, '4 small amount of times', 1, '2 medium amount of times', 1, '2 large amount of times', 1]






        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Mar 26 at 7:10









        Henry YikHenry Yik

        3,2662 gold badges5 silver badges21 bronze badges




        3,2662 gold badges5 silver badges21 bronze badges



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Stack Overflow!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55349136%2fhow-to-increment-through-a-list-and-replace-certain-values-with-their-counts%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Obelisk of Theodosius Contents History Description Notes Bibliography Further reading External links Navigation menuAge of spirituality : late antique and early Christian art, third to seventh centuryOver 60 picturesObelisks of the World41°00′21.24″N 28°58′31.43″E / 41.0059000°N 28.9753972°E / 41.0059000; 28.97539727724550-7235741376235741376

            밀양 대씨 역사 각주 함께 보기 둘러보기 메뉴밀양 대씨

            1973년 목차 사건 문화 탄생 사망 노벨상 달력 둘러보기 메뉴