例如:
def read_file(f):
with open(f, 'r') as file_to_read:
while True:
line = file_to_read.readline()
if line:
yield line
else:
time.sleep(0.1)
Run Code Online (Sandbox Code Playgroud)
生成器由另一个函数使用:
def fun_function(f):
l = read_file(f)
for line in l:
do_fun_stuff()
Run Code Online (Sandbox Code Playgroud)
一个用例将是读取一个无限更新的文本文件,例如日志,其中每秒钟左右添加新行。
据我了解read_file(),只要有结果,该功能就会阻止其他功能。但是由于除非文件中没有新行,否则什么也不做,在这种情况下,这似乎还可以。我的问题是,是否还有其他原因不喜欢这种阻止模式(例如性能)?
给出以下方法
public int calcSum(List<MyClass> items) {
return items.stream()
.mapToInt(i -> i.getHeight())
.sum();
}
Run Code Online (Sandbox Code Playgroud)
我可以使用哪些可以在方法参数中传递的不同getter的选项是什么,这样我就不必getWeight()例如重复相同的return语句?
我当时在考虑使用一种可能会返回吸气剂的其他方法(如果可能的话),但是我很难想到一个好的实现方法。谢谢您的帮助!
之前已经回答过类似的问题,但是我仍然无法弄清楚我的分组和平均方法有什么问题。
我曾尝试多个返回值的组合一样Map<Long, Double>,Map<Long, List<Double>,Map<Long, Map<Long, Double>>,Map<Long, Map<Long, List<Double>>>和那些没有修复错误的IntelliJ我抛出的:“非静态方法不能从静态上下文中引用”。此刻,我觉得我只是在盲目猜测。那么,谁能给我一些关于如何确定正确的回报类型的见解?谢谢!
方法:
public static <T> Map<Long, Double> findAverageInEpochGroup(List<Answer> values, ToIntFunction<? super T> fn) {
return values.stream()
.collect(Collectors.groupingBy(Answer::getCreation_date, Collectors.averagingInt(fn)));
}
Run Code Online (Sandbox Code Playgroud)
答案类别:
@Getter
@Setter
@Builder
public class Answer {
private int view_count;
private int answer_count;
private int score;
private long creation_date;
}
Run Code Online (Sandbox Code Playgroud)