fencepost

Elegant Solutions to the Fencepost Problem (with Strings)

我只是一个虾纸丫 提交于 2019-12-10 21:59:16
问题 What I'm referring to is concatenating String s with a certain String in the middle, such as concatenating sentences separated by a period, or parameter lists with a comma. I know you can use libraries, but sometimes these can't do what you want, like when you want to generate the phrases you are concatenating. So far I've come up with two solutions, StringBuffer sentence = new StringBuffer(); String period = ""; for ( int i = 0; i < sentences.length; i++ ) { sentence.append( period +

What is the pythonic way to detect the last element in a 'for' loop?

蓝咒 提交于 2019-11-26 23:37:05
I'd like to know the best way (more compact and "pythonic" way) to do a special treatment for the last element in a for loop. There is a piece of code that should be called only between elements, being suppressed in the last one. Here is how I currently do it: for i, data in enumerate(data_list): code_that_is_done_for_every_element if i != len(data_list) - 1: code_that_is_done_between_elements Is there any better way? Note: I don't want to make it with hacks such as using reduce . ;) Most of the times it is easier (and cheaper) to make the first iteration the special case instead of the last

What is the pythonic way to detect the last element in a &#39;for&#39; loop?

纵饮孤独 提交于 2019-11-26 08:44:35
问题 I\'d like to know the best way (more compact and \"pythonic\" way) to do a special treatment for the last element in a for loop. There is a piece of code that should be called only between elements, being suppressed in the last one. Here is how I currently do it: for i, data in enumerate(data_list): code_that_is_done_for_every_element if i != len(data_list) - 1: code_that_is_done_between_elements Is there any better way? Note: I don\'t want to make it with hacks such as using reduce . ;) 回答1: