打印同一行而不重复

时间:2018-10-13 19:27:34

标签: python-3.x

我知道这里讨论了很多主题,但是我没有找到解决问题的方法。例如这样的示例代码

            ages = {}
            ages['Sue'] = 23
            ages['Peter'] = 19
            ages['Andrew'] = 78
            ages['Karren'] = 45

            for key in ages:
             if ages[key] >30:
               print("names",key, end = " ")

输出为:姓名安德鲁(Andrew)叫Karren,

操作方法:为安德鲁·卡伦(Andrew Karren)命名

2 个答案:

答案 0 :(得分:1)

您的代码段:

<div className="items">
  {_.times(this.state.items.length, j => ({this.state.items.map(i =><a href="/" id={j} onClick={this.targetValue} className={this.state.selected === j ? "selected" : ""}>{i.name}</a>)}))}
</div>

将为所有 名称打印for key in ages: if ages[key] >30: print("names",key, end = " ") ,例如"names <the-name>"。因此,如果您有多个名字,ages[key] > 30将被打印多次。这就是"names"循环的用途以及它们的作用:它们重复执行代码。

因此,这是有原因的,如果您不希望重复打印文字for,则应该将循环打印"names"的代码移到循环之外。

答案 1 :(得分:1)

ages = {}
ages['Sue'] = 23
ages['Peter'] = 19
ages['Andrew'] = 78
ages['Karren'] = 45

print("names", end=" ") # Take this line out of the loop
for key in ages:
    if ages[key] > 30:
       print(key, end = " ")

输出:
命名安德鲁·卡伦