Posts: 42
Threads: 22
Joined: Oct 2016
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 ?
Posts: 4,229
Threads: 97
Joined: Sep 2016
capitalized = [word.capitalize() for word in numbers]
Posts: 42
Threads: 22
Joined: Oct 2016
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)
Posts: 7,081
Threads: 122
Joined: Sep 2016
Jul-29-2017, 05:34 PM
(This post was last modified: Jul-29-2017, 05:35 PM by snippsat.)
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.
Posts: 2,015
Threads: 9
Joined: May 2017
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)))
Posts: 2,955
Threads: 48
Joined: Sep 2016
Jul-31-2017, 02:12 PM
(This post was last modified: Jul-31-2017, 02:12 PM by wavic.)
capitalized = [word.capitalize() if numbers.index(word) < 10 else word for word in numbers]
Posts: 8,089
Threads: 154
Joined: Sep 2016
(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)]
Posts: 2,955
Threads: 48
Joined: Sep 2016
(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
|