我有两个字符串列表listA
和listB
。 listA
更长,我想通过添加空字符串使listB
大小相同。
这有效:
int diff = listA.size() - listB.size()
for (int i = 0; i < diff; i++) {
listB.add("");
}
但这并不是:
for (int i = 0; i < (listA.size() - listB.size()); i++) {
listB.add("");
}
为什么?
答案 0 :(得分:9)
变量diff
的第一个例子是常量,而第二个例子是在循环的每次迭代中评估条件,因此你在迭代过程中重新添加对象的大小列表的内容会发生变化,因此两个代码片段都不会做同样的事情。
我建议您继续使用第一种方法,即事先缓存循环条件的限制,而不是在每次迭代期间重新评估它。
答案 1 :(得分:0)
当您向itemList.index
添加新值时,大小将递增,因此在每个循环中,for循环重新评估itemList.head()
的大小以查找条件是否为{{1}停止循环。在这种情况下,条件将永远为2 Horseradish
2 Rutabaga
2 Turnip
0 Chickpeas
0 Pinto beans
,因为您将新元素添加到列表
答案 2 :(得分:0)
每次list.add(&#34;&#34;)被调用时,List的大小会递增
所有内容(listB.size() - listB.size())每次通过迭代都计算列表的新大小 一世。 e listB获得新的大小。
从您的代码段diff ==您想要将项目添加到listB的剩余大小
选项1可以。
答案 3 :(得分:0)
其他答案已经解释了为什么你的第二个循环不起作用。
我想建议一种使用from apscheduler.schedulers.background import BlockingScheduler
count = 0
N = 10 # Change this per your requirement
def run_external_process():
global count, scheduler
# Execute the job N times
count = count + 1
if count == 10: # Shutdown the scheduler and exit
scheduler.shutdown(wait=False)
sys.exit(1)
#Run your code here
# When each job is executed check for its output
def listen_for_output():
if event.retval: # Check the return value of your external process
# Collect output
else:
# Call script to terminate process
try:
scheduler = BlockingScheduler() # Initiate your scheduler
except ImportError:
raise ImportError('Failed to import module')
sys.exit(1)
scheduler.add_job(run_external_process, 'interval', seconds=1, id='my_job_id')
# Add a listener to check the output of your external process
scheduler.add_listener(listen_for_output, EVENT_JOB_EXECUTED|EVENT_JOB_ERROR)
scheduler.start()
和Collections.nCopies
消除循环的替代方法:
List.addAll
或
if (listA.size() - listB.size() > 0) {
listB.addAll(Collections.nCopies(listA.size() - listB.size(), ""));
}