列表理解中的多个条件和结果?

时间:2017-03-19 14:12:52

标签: python python-3.x

任何人都可以纠正这个吗?看看我哪里错了?

datFiles <- c(list.files(path = "c:/Users/Philip/Downloads/Tornadoes/",
    pattern = "StormEvents_details.*\\.csv$",
    all.files = FALSE, full.names = TRUE, recursive = FALSE, ignore.case = TRUE,
    include.dirs = FALSE, no.. = FALSE))

for (i in 1:length(datFiles)) {
    x[i] <- read.csv(datFiles[i])
    n[i] <- length(select(x[i], EVENT_TYPE) %>% filter(EVENT_TYPE=="Tornado") %>% unlist)
    <your code here>
}

最终应该:

row_length = 4
ic = 1
pc = 2

newlist = [('') if not x == ic and not x == pc else ('RESERVED ID')
if x == ic ('RESERVED PARENT') if x == pc for x in range(row_length)]

1 个答案:

答案 0 :(得分:1)

这是你在找什么?

newlist = [''] * row_length
newlist[ic-1] = 'RESERVED ID'
newlist[pc-1] = 'RESERVED PARENT'

并非所有事情都必须在列表理解中完成。我的代码不仅效率更高,更重要的是易于阅读。

编辑这是你的单行。但请不要!善待那些有时会阅读你的代码的潜在人:

newlist = ['RESERVED ID' if idx == ic-1 else 'RESERVED PARENT' if idx == pc-1 else '' for idx in range(row_length)]