所以现在我有一个正常运行的代码,如果一个子字符串(在子字符串列表中)存在于另一个更长的字符串中,它会将1附加到给定列表。
例如,如果我想确定在棒球比赛中击球的位置,并使用以下字符串作为输入:
public class Youtube_Player_Activity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
String url = "";
@Override
protected void onCreate(Bundle arg0) {
// TODO Auto-generated method stub
super.onCreate(arg0);
setContentView(R.layout.youtube_player_activity);
Bundle bundle = getIntent().getExtras();
if(bundle != null)
{
url = bundle.getString("URL");
}
YouTubePlayerView youTubeView = (YouTubePlayerView) findViewById(R.id.videoView1);
youTubeView.initialize(SecurityInfo.DEVELOPER_KEY, this);
}
.....
}
我可以简单地使用any()函数,如下所示,确定是否有第一个参与游戏:
s = 'SMITH grounded out to 1b.'
然而,让我们说:
first = []
first_ids = ['1b', 'first base']
if any(idx in s for idx in first_ids):
first.append(1)
else:
first.append(0)
现在,我们遇到涉及多个职位的情况,我只想包括第一个职位。识别ss(游击手)和p(投手)的过程与1b完全相同。我的想法是通过识别满足any()函数的子字符串的索引来简单地找到哪个位置。有一种简单的方法吗?
答案 0 :(得分:1)
我认为最好的方法是保留所有职位列表,拆分数据,然后过滤:
positions = ['1b', '2b', '3b', 'ss', 'p', 'c', 'lf', 'rf', 'cf']
s = 'SMITH grounded into double play 1b to ss to p.'
string_positions = [i for i in s.strip('.').split() if i in positions]
print string_positions
print string_positions[0]
输出:
['1b', 'ss', 'p']
'1b'