Python Forum

Full Version: How can I do it easier ?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have a list. I need to change my list so that the first ten elems is becoming with a capital letter. I'm doing it this way:
numbers = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thriteen', 'fourteen', 'fivteen']
first_ten = numbers[:10]

capitalize_first_ten =
for x in first_ten:
    capitalize_first_ten.append(x.capitalize())

tmp = list_[10:]
print(list_)
print(capitalize_first_ten + tmp)
I'm sure there are a better way than mine. How would you make it ?
capitalized = [word.capitalize() for word in numbers]
I reduced the code.
numbers = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thriteen', 'fourteen', 'fivteen']
tmp = [x.capitalize() for x numbers[:10]]
numbers = tmp + numbers[:10]
print(numbers)
numbers = ['one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten', 'eleven', 'twelve', 'thriteen', 'fourteen', 'fivteen']
>>> print([x.capitalize() for x in numbers[:10] * 2])
['One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten', 'One', 'Two', 'Three', 'Four', 'Five', 'Six', 'Seven', 'Eight', 'Nine', 'Ten']
Or it's okay that way if want 1 capitalize with and 1 with lower case.
Example with islice and chain from itertools:

from itertools import islice
from itertools import chain

new_list = list(chain((x.capitalize() for x in islice(numbers, 0, 10)), islice(numbers, 10)))
capitalized = [word.capitalize() if numbers.index(word) < 10 else word for word in numbers]
(Jul-31-2017, 02:12 PM)wavic Wrote: [ -> ]capitalized = [word.capitalize() if numbers.index(word) < 10 else word for word in numbers]
I think it's better like this
capitalized = [word.capitalize() if i < 10 else word for i, word in enumerate(numbers)]
(Jul-31-2017, 03:45 PM)buran Wrote: [ -> ]
(Jul-31-2017, 02:12 PM)wavic Wrote: [ -> ]capitalized = [word.capitalize() if numbers.index(word) < 10 else word for word in numbers]
I think it's better like this
capitalized = [word.capitalize() if i < 10 else word for i, word in enumerate(numbers)]
 

I was lazy