我必须编写一个Python代码,有一个函数,它接收一个元组作为参数,其中元组的所有元素都是numpy数组。该代码的输出将为我提供来自该元组的独特爱好。但是如果我使用 dtype = str 来创建一个新数组,它只需要元素的第一个字母,但如果我使用 dtype = object 那么它可以解决问题
def analyzeHobbies(* participants): #(* arguments) is used for variable number of parameters
length = len(participants)
total = 0
for i in range(length):
total = total+ len(participants[i])
new = np.zeros (total, dtype = object)
count = 0
for j in range(length):
for k in range(len(participants[j])):
new[count] = participants[j][k]
count += 1
unique1 = np.zeros (total, dtype = object)
unique1[0] = new[0]
for h in range(1,total):
if new[h] not in unique1:
unique1[h] = new[h]
else:
unique1[h] = "0"
count = 0
for l in range(len(unique1)):
if unique1[l]!= "0":
count = count+1
final = np.zeros (count, dtype = object)
index = 0
for m in range(len(unique1)):
if unique1[m] != "0":
final[index] = unique1[m]
index = index+1
print(f"""Unique Activities in the Town:
{final}""")
print("Statistics:")
for n in range(count):
count1 = 0
for o in range(len(new)):
if final[n] == new[o]:
count1 = count1+1
print(f"{count1}participant(s) like(s){final[n]} ")
print("/// Task 04: Get Those Hobbies ///")
participant_1 = np.array( ["Hiking", "Reading", "Photography", "Cooking"])
participant_2 = np.array( ["Reading", "Hiking", "Painting"])
participant_3 = np.array( ["Hiking", "Cooking", "Photography"])
print(f'Task 4:')
analyzeHobbies(participant_1, participant_2, participant_3) #
这应该打印出来
Unique Activities in the Town:
['Photography', 'Painting', 'Cooking', 'Reading', 'Hiking']
Statistics:
2 participant(s) like(s) Photography.
1 participant(s) like(s) Painting.
2 participant(s) like(s) Cooking.
2 participant(s) like(s) Reading.
3 participant(s) like(s) Hiking.
我就是这样做的。不使用对象可以解决这个问题吗?
处理此问题的最佳方法是跳过 numpy 并使用
collections.Counter
,它正是针对这种情况创建的。
import collections
import numpy as np
def analyzeHobbies(* participants):
unique = collections.Counter()
for p in participants:
unique.update(p)
print("Unique Activities in the Town:")
print(list(unique.keys()))
print("Statistics:")
for k,v in unique.items():
print(f"{v} participant(s) like(s) {k}")
print("/// Task 04: Get Those Hobbies ///")
participant_1 = np.array( ["Hiking", "Reading", "Photography", "Cooking"])
participant_2 = np.array( ["Reading", "Hiking", "Painting"])
participant_3 = np.array( ["Hiking", "Cooking", "Photography"])
print(f'Task 4:')
analyzeHobbies(participant_1, participant_2, participant_3) #
输出:
/// Task 04: Get Those Hobbies ///
Task 4:
Unique Activities in the Town:
['Hiking', 'Reading', 'Photography', 'Cooking', 'Painting']
Statistics:
3 participant(s) like(s) Hiking
2 participant(s) like(s) Reading
2 participant(s) like(s) Photography
2 participant(s) like(s) Cooking
1 participant(s) like(s) Painting