我正在尝试编写一种方法,该方法将计算一组数据的模式并将其返回。如果没有模式或一个以上模式(例如:如果4和2返回的次数最多)I,则希望该函数返回Double.NaN。我能够获得该模式,但是如果存在多个模式,则无法使我的代码返回Double NaN。
这是我的代码!
Meu = []
def getting_friends_follwers():
# Get list of followers and following for group of users tweepy
f = open("amigos.txt","w")
cursor = tweepy.Cursor(api.friends, screen_name="Carlos")
cursor2 = tweepy.Cursor(api.followers, screen_name="Carlos")
## for user in cursor.items():
## print('friend: ' + user.screen_name)
for user in sorted(cursor2.items(100)):###funciona se eu tirar este valor!!!
f.write(str(user.screen_name)+ "\n")
print('follower: ' + user.screen_name)
f.close()
getting_friends_follwers()
答案 0 :(得分:0)
我假设您正在使用Java。
我们可以通过简单地创建一个Double.NaN
来找到模式(以及您返回Map
的限制),其中键是各个数据点,值是它们在数据中的对应计数数组。
Stream
在编写可读和简洁的代码方面将非常有用。
如果您要对array / ArrayList中的每个成员进行计数,则可以根据需要简单地使用此计数得出结论。
请参阅以下实现上述说明的代码:
public static Double mode(List<Double> data) {
if (data.isEmpty()) {
// returning NaN if the input arraylist is empty
return Double.NaN;
}
Map<Double, Integer> count = new HashMap<>();
data.forEach(
i -> {
count.putIfAbsent(i, 1);
count.put(i, count.get(i) + 1);
}
);
int maxCount = count.values().stream().max(Integer::compare).get(); // this assumes that the data is not empty
if (count.values().stream().filter(i -> i == maxCount).count() > 1) {
// more than one mode present
return Double.NaN;
}
// here we'll be sure that only one mode exists
return count
.entrySet()
.stream()
.filter(e -> e.getValue() == maxCount)
.findFirst() // as we've only one mode
.get()
.getKey();
}