用 K 递增数字字符串的Python程序
给定字符串列表,编写一个Python程序,以 K 递增数字字符串。
例子:
Input : test_list = [“gfg”, “234”, “is”, “98”, “123”, “best”, “4”], K = 6
Output : [‘gfg’, ‘240’, ‘is’, ‘104’, ‘129’, ‘best’, ’10’]
Explanation : 234, 98 and 4 are incremented by 6 in result.
Input : test_list = [“gfg”, “234”, “is”, “98”, “123”, “best”, “4”], K = 4
Output : [‘gfg’, ‘238’, ‘is’, ‘102’, ‘129’, ‘best’, ‘8’]
Explanation : 234, 98 and 4 are incremented by 4 in result.
方法 #1:使用str() + int() + loop + isdigit()
在这里,我们使用 str() + int() 执行元素相互转换的任务,并使用 isdigit() 检查数字,使用循环完成迭代。
Python3
# Python3 code to demonstrate working of
# Increment Numeric Strings by K
# Using str() + int() + loop + isdigit()
# initializing Matrix
test_list = ["gfg", "234", "is", "98", "123", "best", "4"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 6
res = []
for ele in test_list:
# incrementing on testing for digit.
if ele.isdigit():
res.append(str(int(ele) + K))
else:
res.append(ele)
# printing result
print("Incremented Numeric Strings : " + str(res))
Python3
# Python3 code to demonstrate working of
# Increment Numeric Strings by K
# Using list comprehension + isdigit()
# initializing Matrix
test_list = ["gfg", "234", "is", "98", "123", "best", "4"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 6
# increment Numeric digits.
res = [str(int(ele) + K) if ele.isdigit() else ele for ele in test_list]
# printing result
print("Incremented Numeric Strings : " + str(res))
输出:
The original list is : [‘gfg’, ‘234’, ‘is’, ’98’, ‘123’, ‘best’, ‘4’]
Incremented Numeric Strings : [‘gfg’, ‘240’, ‘is’, ‘104’, ‘129’, ‘best’, ’10’]
方法 #2:使用列表理解+ isdigit()
这是可以执行此任务的方法之一。与上面类似,只需一行替代使用列表理解来压缩解决方案。
蟒蛇3
# Python3 code to demonstrate working of
# Increment Numeric Strings by K
# Using list comprehension + isdigit()
# initializing Matrix
test_list = ["gfg", "234", "is", "98", "123", "best", "4"]
# printing original list
print("The original list is : " + str(test_list))
# initializing K
K = 6
# increment Numeric digits.
res = [str(int(ele) + K) if ele.isdigit() else ele for ele in test_list]
# printing result
print("Incremented Numeric Strings : " + str(res))
输出:
The original list is : [‘gfg’, ‘234’, ‘is’, ’98’, ‘123’, ‘best’, ‘4’]
Incremented Numeric Strings : [‘gfg’, ‘240’, ‘is’, ‘104’, ‘129’, ‘best’, ’10’]