如果存在子串,则python查找并替换列表项

时间:2017-12-20 12:10:02

标签: python string python-3.x list substring

我想替换包含某个子字符串的列表中的项目。在这种情况下,任何形式的包含“NSW”(大写字母都很重要)的项目应替换为“NSW = 0”。原始条目是“NSW = 500”还是“NSW = 501”并不重要。我可以找到列表项,但不知何故,我找不到列表中的位置,所以我可以替换它?这就是我提出的,但我替换了所有项目:

function column(){
  var cell1={x0:21,y0:25,x1:163,y1:165};
var x=$('#x').html();
var y=$('#y').html();
/*
  console.log(x);
  console.log(y);
  console.log(cell1['x0']);
  console.log(cell1['x1']);
  console.log(cell1['y0']);
  console.log(cell1['y1']);
*/
if (x>=cell1['x0'] && x<=cell1['x1'] && y>=cell1['y0'] && y<=cell1['y1'])
{
console.log('cell oone');
}
else {
console.log('other cell');

}

3 个答案:

答案 0 :(得分:3)

简单<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/main" //add this android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_margin="10dp" android:clickable="true" //add this android:focusable="true" //add this android:elevation="4dp"> ... ... <ImageView android:id="@+id/img_download" android:clickable="true" //add this android:focusable="true" //add this android:layout_width="25dp" android:layout_height="25dp" android:layout_margin="5dp" android:tint="@color/primary" app:layout_constraintBottom_toBottomOf="parent" app:layout_constraintEnd_toEndOf="parent" app:layout_constraintTop_toTopOf="parent" app:srcCompat="@drawable/ic_drawer_download" /> </android.support.constraint.ConstraintLayout>

list comprehension

#driver values:

>>> ["NSW = 0" if "NSW" in ele else ele for ele in l]

答案 1 :(得分:1)

any不会为您提供索引,并且在每次迭代时始终为true。所以放弃它......

就个人而言,我会使用列表理解与三元组来决定保留原始数据或替换为NSW = 0

my_list =["abc 123","acd 234","NSW = 500", "stuff","morestuff"]

result = ["NSW = 0" if "NSW" in x else x for x in my_list]

结果:

['abc 123', 'acd 234', 'NSW = 0', 'stuff', 'morestuff']

答案 2 :(得分:1)

另一个解决方案: 的

from __future__ import division, print_function, with_statement
my_list =["abc 123","acd 234","NSW = 500", "stuff","morestuff"]
for index in xrange(len(my_list)):
    if "NSW" in my_list[index]:
        my_list[index] = "NSW = 0"

print (my_list)  

<强>输出:

['abc 123', 'acd 234', 'NSW = 0', 'stuff', 'morestuff']

或者你可以按目的使用列表理解:

<强>码

my_list =["abc 123","acd 234","NSW = 500", "stuff","morestuff"]

print ["NSW = 0" if "NSW" in _ else _ for _ in my_list]

<强>输出:

['abc 123', 'acd 234', 'NSW = 0', 'stuff', 'morestuff']