给定一个数字列表nums,请编写一个函数,将它们中的每个元素加上自己的位置编号(从1开始)。例如第一个元素加1,第二个元素加2,以此类推。并且,如果增量结果是多位数,则只保留末尾数字。
示例:
输入:[1, 2, 3]
,输出:[2, 4, 6]
。因为[1+1, 2+2, 3+3]
输入:[3, 6, 9, 8, 9]
,输出:[4, 8, 2, 2, 4]
。
题目难度:简单
题目来源:CodeWar: Incrementer
def solution(nums: list) -> list:
# your code
assert solution([1, 2, 3]) == [2, 4, 6]
assert solution([4, 6, 7, 1, 3]) == [5, 8, 0, 5, 8]
assert solution([3, 6, 9, 8, 9]) == [4, 8, 2, 2, 4]
nobugs
2
def solution(nums: list) -> list:
return [nums[i] + i + 1 if nums[i] + i + 1 < 9 else int(str(nums[i] + i + 1)[-1]) for i in range(len(nums))]
assert solution([1, 2, 3]) == [2, 4, 6]
assert solution([4, 6, 7, 1, 3]) == [5, 8, 0, 5, 8]
assert solution([3, 6, 9, 8, 9]) == [4, 8, 2, 2, 4]
Kawi
3
def solution(nums: list) -> list:
# your code
num = []
for i, j in enumerate(nums): num.insert(i, (j + i + 1) % 10)
return num
1 个赞
Huis
4
def solution(nums: list) -> list:
return [(nums[i]+i+1)%10 for i in range(len(nums))]
1 个赞
Mooii
5
def solution(nums: list) -> list:
for i in range(0,len(nums)):
nums[i] = (nums[i]+i+1) % 10
return nums
assert solution([1, 2, 3]) == [2, 4, 6]
assert solution([4, 6, 7, 1, 3]) == [5, 8, 0, 5, 8]
assert solution([3, 6, 9, 8, 9]) == [4, 8, 2, 2, 4]
def solution(nums: list) -> list:
return [int(list(str(nums[i] + i+1))[-1]) for i in range(0, len(nums))]
assert solution([1, 2, 3]) == [2, 4, 6]
assert solution([4, 6, 7, 1, 3]) == [5, 8, 0, 5, 8]
assert solution([3, 6, 9, 8, 9]) == [4, 8, 2, 2, 4]
def solution(nums: list) -> list:
return [nums[i] + i + 1 if nums[i] + i + 1 < 10 else int(str(nums[i] + i + 1)[-1]) for i in range(len(nums))]
assert solution([1, 2, 3]) == [2, 4, 6]
assert solution([4, 6, 7, 1, 3]) == [5, 8, 0, 5, 8]
assert solution([3, 6, 9, 8, 9]) == [4, 8, 2, 2, 4]
def solution11(ll_in:list):
ll_out=[]
i=0
while i < len(ll_in):
num=ll_in[i]+(i+1)
if num >=10:
ll_out.append(int(str(num)[-1]))
else:
ll_out.append(num)
i+=1
return ll_out
assert solution11([1, 2, 3]) == [2, 4, 6]
assert solution11([4, 6, 7, 1, 3]) == [5, 8, 0, 5, 8]
assert solution11([3, 6, 9, 8, 9]) == [4, 8, 2, 2, 4]
kary
9
def solution(nums: list) -> list:
# your code
# zip函数将多个列表视为一个整体,遍历时,同时从各个列表里取出相同索引位置的元素
calculation_nums = [x + y for x, y in zip([j + 1 for j in range(len(nums))], nums)]
# 将整数转换为字符串,取最后一个索引值,然后再转换为整数
new_nums = [int(str(j)[-1]) for j in calculation_nums]
return new_nums
assert solution([1, 2, 3]) == [2, 4, 6]
assert solution([4, 6, 7, 1, 3]) == [5, 8, 0, 5, 8]
assert solution([3, 6, 9, 8, 9]) == [4, 8, 2, 2, 4]
lekaixin
(ALe阿乐)
10
def solution(nums: list) -> list:
return [int(str(i+nums[i]+1)[-1]) for i in range(len(nums))]
assert solution([1, 2, 3]) == [2, 4, 6]
assert solution([4, 6, 7, 1, 3]) == [5, 8, 0, 5, 8]
assert solution([3, 6, 9, 8, 9]) == [4, 8, 2, 2, 4]