代码
library(dplyr)
df <- tibble(a = c(2, 3, 2, 1, 0),
b = c(2, 3, 3, 2, 1),
z = c(3, 2, 1, 1, 0))
df <- df %>%
mutate(sum_values = case_when((a > 1 | b > 1) & (z > 0) ~ (a+b+z),
TRUE ~ 0))
结果
fav_numbers = {
'bill': [4,6,7,1],
'uros': [9,0,1,2],
'pera': [1,6,3,5],
}
for name, numbers in fav_numbers.items():
print(name.title())
for num in numbers:
print(num, end=' ')
问题 如何编写for循环,以便最后两个名称正确格式化?
答案 0 :(得分:3)
只需在循环末尾添加另一个print
即可开始新行:
for name, numbers in fav_numbers.items():
print(name.title())
for num in numbers:
print(num, end=' ')
print()
在这里live
答案 1 :(得分:2)
fav_numbers = {
'bill': [4,6,7,1],
'uros': [9,0,1,2],
'pera': [1,6,3,5],
}
for k,v in fav_numbers.items():
print(k, *v)
输出
bill 4 6 7 1
uros 9 0 1 2
pera 1 6 3 5
答案 2 :(得分:2)
问题不是end=' '
,而是缺少它的print(name.title())
。还要添加end= '
,以便将数字打印到同一行中,然后以print()
结尾作为最后的换行符。
for name, numbers in fav_numbers.items():
print(name.title(), end=' ') # no newline here
for num in numbers:
print(num, end=' ')
print() # but newline here
或者,您可以使用不带特殊参数的print
,并使用numbers
将*
作为var-arg参数传递。
for name, numbers in fav_numbers.items():
print(name.title(), *numbers)
这将打印姓名和单个数字,所有数字均用空格分隔。两种方式的输出均为:
Pera 1 6 3 5
Bill 4 6 7 1
Uros 9 0 1 2
答案 3 :(得分:0)
format
非常适合以特定格式打印
for name,numbers in fav_numbers.items():
print('{}: {}'.format(name,' '.join((str(n) for n in numbers))))
bill: 4 6 7 1
uros: 9 0 1 2
pera: 1 6 3 5
答案 4 :(得分:0)
fav_numbers = {
'bill': [4,6,7,1],
'uros': [9,0,1,2],
'pera': [1,6,3,5],
}
for name,numbers in fav_numbers.items():
print(", ".join( repr(e) for e in numbers ).replace(',',''),name)
输出
4 6 7 1 bill
9 0 1 2 uros
1 6 3 5 pera