简体   繁体   English

通过引用另一个列表中存在的次数来显示列表中的项目。

[英]Display an item in a list by referring to the number of times present in another list.

I am trying to display each item in string_list. 我正在尝试在string_list中显示每个项目。 But the number of times to display each item is in display_times list. 但是显示每个项目的次数在display_times列表中。 The code should display a 2 times, b 3 times and c once. 该代码应显示a 2次,b 3次,c显示一次。 This is what I have got which is not correct. 这是我所得到的是不正确的。 What should I do next? 接下来我该怎么办?

string_list = ['a', 'b', 'c']
display_times = ['2', '3', '1']

for item in string_list:
    for times in display_times:
        print("It is " + item)

Here's a solution 这是一个解决方案

In [12]: for s, t in zip(string_list, display_times):
    for i in range(int(t)):
        print "It is %s" % s
   ....:         
It is a
It is a
It is b
It is b
It is b
It is c

I think this is a good understandable way to do it: 我认为这是一种很好的可以理解的方式:

zipped = zip(string_list, display_times) #equal to [('a', '2'), ('b', '3'), ('c', '1')]
for value, time in zipped:
    for i in range(int(time)):
        print value

result: 结果:

a
a
b
b
b
c

The first problem you have that is the display_times list is storing strings and not numbers. 您遇到的第一个问题是display_times列表是存储字符串而不是数字。

There are lots of shortcut ways to do this, but lets start with the easy way: 有很多捷径可以做到这一点,但让我们从简单的方法开始:

>>> for position,item in enumerate(string_list):
...     how_many = int(display_times[position])
...     print('It is {}'.format(item*how_many))
...
It is aa
It is bbb
It is c

You can use zip to combine the two lists: 您可以使用zip合并两个列表:

>>> zip(string_list, display_times)
[('a', '2'), ('b', '3'), ('c', '1')]

Now you can do: 现在您可以执行以下操作:

>>> for item,how_many in zip(string_list, display_times):
...     print('It is {}'.format(item*int(how_many)))
...
It is aa
It is bbb
It is c

There are lot of other ways but they will all involve some variation of the above two. 还有很多其他方法,但是它们都将涉及上述两种方法的一些变化。

for i, v in enumerate(display_times):
    for j in range(int(v)):
        print (string_list[i])

Or using a LC: 或使用LC:

r = [[string_list[i] for j in range(int(v))] for i,v in enumerate(display_times)]
for i in r:
   print (i)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM