Python Forum
Replace slice in list comperhensions
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Replace slice in list comperhensions
#1
Is there a better way of replacing [-2] position which is == '1' with '2'.
numbers = ['10237310', '10230010']
newlist = [b[0:-2] + '2' + b[-1] for b in numbers if b[-2] == '1']
['10237320', '10230020']
Reply
#2
This might be a little faster (''.join() is faster than + for strings I think):
newlist=[''.join((b[0:-2],'2',b[-1])) for b in numbers if b[-2]=='1']
Strings are immutable, so you can convert to list('10237320') of string characters (or convert each character to an integer) to make more editable in general if needed.
Reply
#3
(Nov-06-2017, 03:29 AM)ineedastupidusername Wrote: This might be a little faster (''.join() is faster than + for strings I think):
newlist=[''.join((b[0:-2],'2',b[-1])) for b in numbers if b[-2]=='1']
Strings are immutable, so you can convert to list('10237320') of string characters (or convert each character to an integer) to make more editable in general if needed.

You right maybe this one:
newlist = [int(b) + 10 for b in numbers if b[-2] == '1']
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Fix pandas copy/slice warning. deanhystad 3 840 Sep-07-2023, 03:18 PM
Last Post: deanhystad
  Slice creates new objects? fmr300 4 1,326 Jul-20-2022, 12:34 PM
Last Post: fmr300
  InvalidIndexError: (slice(None, None, None), slice(None, -1, None)) SuperNinja3I3 1 4,441 Jul-15-2022, 05:59 AM
Last Post: Larz60+
  Slice list Moris526 1 1,654 Dec-24-2020, 02:19 AM
Last Post: deanhystad
  increase and decrease a slice value? KEYS 2 2,105 Nov-10-2020, 11:35 PM
Last Post: KEYS
  Compare Two Lists and Replace Items In a List by Index nagymusic 2 2,895 May-10-2020, 05:28 AM
Last Post: deanhystad
  Pass Tuple as a Slice nagymusic 2 2,373 Dec-12-2019, 04:42 AM
Last Post: nagymusic
  Preferred way to slice a list SvetlanaofVodianova 3 2,559 Dec-09-2019, 11:50 PM
Last Post: SvetlanaofVodianova
  slice python array on condition Gigux 2 2,271 Nov-03-2019, 07:21 PM
Last Post: Larz60+
  How do you replace a word after a match from a list of words in each line of a file? vijju56 1 3,477 Oct-17-2019, 03:04 PM
Last Post: baquerik

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020