使用列表推导,我要打印偶数,同时字符串表示偶数为“ Even”,而奇数表示为“ Odd”

时间:2019-07-23 14:53:57

标签: python python-3.x list-comprehension

使用列表推导功能,我要打印偶数,其中字符串表示偶数为“ Even”,而奇数表示为“ Odd”

使用以下代码-我得到的只是偶数和奇数。只是想知道我是否可以同时获得两个值并说明它们的偶数/奇数。

obj = ["Even" if i%2==0 else "odd" for i  in range(20)] 
print(obj)

仅使用列表理解。

5 个答案:

答案 0 :(得分:1)

好的。

"AMERICANO", "LATTE", "CAPPUCCINO" 
or "ESPRESSO", "RISTRETTO", "AMERICANO"
not "AMERICANO" "ESPRESSO"
  

[(0,'even'),(1,'odd'),(2,'even'),(3,'odd'),(4,'even'),(5,'odd' ),(6,``偶数''),(7,``奇数''),(8,``偶数''),(9,``奇数''),(10,``偶数''),(11,``奇数''), (12,'even'),(13,'odd'),(14,'even'),(15,'odd'),(16,'even'),(17,'odd'),(18 ,“偶数”),(19,“奇数”)]

或者,如果您愿意的话,甚至按照字典:

obj = [(i,"even" if i%2==0 else "odd") for i in range(20)]
print(obj)
  

{0:“偶数”,1:“奇数”,2:“偶数”,3:“奇数”,4:“偶数”,5:“奇数”,6:“偶数”,7:“奇数” ',8:'偶数',9:'奇数',10:'偶数',11:'奇数',12:'偶数',13:'奇数',14:'偶数',15:'奇数', 16:'even',17:'odd',18:'even',19:'odd'}

答案 1 :(得分:0)

obj = ["Even" if i%2==0 else "odd" for i in range(20)]
print(list(enumerate(obj))) # [(0, 'Even'), (1, 'odd'), (2, 'Even'), (3, 'odd'), (4, 'Even'), (5, 'odd'), (6, 'Even'), (7, 'odd'), (8, 'Even'), ...

或:

obj = ["Even" if i%2==0 else "odd" for i in range(20)]

for key,value in enumerate(obj):
    print ("{} is {} number".format(key,value))

输出:

0 is Even number
1 is odd number
2 is Even number
3 is odd number
4 is Even number
5 is odd number
6 is Even number
7 is odd number
8 is Even number
9 is odd number
10 is Even number
11 is odd number
12 is Even number
13 is odd number
14 is Even number
15 is odd number
16 is Even number
17 is odd number
18 is Even number
19 is odd number

答案 2 :(得分:0)

您可以尝试使用元组:

obj = [(i, "Even") if i%2==0 else (i, "odd") for i in range(20)] 
print(obj)

答案 3 :(得分:0)

print('\n'.join(str(i) + {0:' is even', 1:' is odd'}[i&1] for i in range(20)))

或者:

from itertools import cycle

c = cycle([' is even', ' is odd'])
print('\n'.join(str(i) + msg for i, msg in zip(range(20), c)))

打印:

0 is even
1 is odd
2 is even
3 is odd
4 is even
5 is odd
6 is even
7 is odd
8 is even
9 is odd
10 is even
11 is odd
12 is even
13 is odd
14 is even
15 is odd
16 is even
17 is odd
18 is even
19 is odd

答案 4 :(得分:0)

我只用了自己的代码,并将字符串连接到结果中。您做对了。

>>> obj = [f"{i} is Even" if i%2==0 else f"{i} is odd" for i  in range(20)]
>>> print('\n'.join(obj))
0 is Even
1 is odd
2 is Even
3 is odd
4 is Even
5 is odd
6 is Even
7 is odd
8 is Even
9 is odd
10 is Even
11 is odd
12 is Even
13 is odd
14 is Even
15 is odd
16 is Even
17 is odd
18 is Even
19 is odd

python中有很多字符串连接方法,您可以从这个Which is the preferred way to concatenate a string in Python?问题中了解更多信息。我在这里使用了Python f'strings。