此代码可能存在很多问题,无法在单个帖子中回答。我的主要问题是我试图通过列表理解来减少for循环的数量。
var drinksToday: MutableList<String> = mutableListOf()
lateinit var adapter: ArrayAdapter<String>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
addButton.setOnClickListener {
drinksToday.add(0, "250 ml")
// Print to check addition to list
println(drinksToday.toString())
}
if (savedInstanceState != null) {
savedInstanceState.run {
val list = getStringArray(EXTRA_LIST)
if (list != null) {
drinksToday = list.toMutableList<String>()
}
}
}
adapter = ArrayAdapter(this, android.R.layout.simple_list_item_1, drinksToday)
drinksTodayList.adapter = adapter
}
override fun onSaveInstanceState(outState: Bundle?) {
super.onSaveInstanceState(outState)
outState?.run {
putStringArray(EXTRA_LIST, drinksToday.toTypedArray())
}
}
答案 0 :(得分:2)
列表理解并不是唯一的改进。也可以通过直接在元素上进行迭代来摆脱for i in len(range(reqSoupElems))
反图案:
time = [timeRegex.search(str(element)).group() for element in reqSoupElems]