我有一个数字列表,我想计算一下附近有多少相同的物品。 然后,我想创建一个新列表,该列表将数字中出现的次数相乘。
列表[1, 2, 2, 3, 4, 4, 3]
输出将为[1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4, 3, 3, 3]
def multiply_lst(lst):
new_lst = []
counter = 1
for i in range(len(lst)-1):
if lst[i] == lst[i+1]
counter+=1
else:
new_lst += lst[i]*(1*lst[i])
new_lst += [lst[i]]*(counter*lst[i])
return new_lst
答案 0 :(得分:0)
这可能很复杂,但您也可以通过遵循以下解决方案来实现自己的目标:
def multiply_lst(given_list):
counter_list = [] # list to collect counter for each of the different numbers
different_numbers_list = [given_list[0]] # list collect each of the different numbers and add the first different number from given_list
result_list = [] # list for the result
count = 1 # set count to 1
# loop through the given list
for i in range(1, len(given_list)):
# if current number and next number are same add 1 to count
if given_list[i] == given_list[i-1]:
count += 1
# else the number to different_numbers_list and add the counter for the number to counter_list and then set count to 1
else:
different_numbers_list.append(given_list[i])
counter_list.append(count)
count = 1
counter_list.append(count) # add the last different number's count to the counter_list
# finally add items from different_numbers_list, (item * items_counter from counter_list) times to result_list
for i in range(len(different_numbers_list)):
for j in range(counter_list[i]*different_numbers_list[i]):
result_list.append(different_numbers_list[i])
return result_list
lst = [1, 2, 2, 3, 4, 4, 3] # given list
print(multiply_lst(lst))
答案 1 :(得分:-1)
您可以在列表中添加一个新列表,其中包含重复<selector
<item
android:state_pressed="false"
android:drawable="@drawable/ic_normal_button"
<item
android:state_pressed="true"
android:drawable="@drawable/ic_pressed_button"/>
</selector>
次的数字x
。
x